Backbone Marionette different composite views

▼魔方 西西 提交于 2019-12-12 09:54:43

问题


Is it possible to have a composite view in marionette with DIFFERENT item views inside? For example:

var myCompositeView = Backbone.Marionette.CompositeView.extend({
    template: Handlebars.compile(myTemplate),
    itemView: myView, // I want different views, not just myView
    initialize: function(){
        this.collection = this.model.views;
    },
    appendHtml: function(collectionView, itemView){
        collectionView.$('.container').append(itemView.el);
    }

});

Basically, depending on the model in the collection, I want to create a certain view.


回答1:


You can accomplish this with the getItemView method:

var VTbody = Backbone.Marionette.CompositeView.extend({
    template: "#emptyTemplate",
    tagName:"tbody",
    //itemView:VTr,  /*No need to specify item View */
    getItemView: function(item){
      if(item.get("type")=="details") {
            return  VTrDetails
        } else  {
            return VTr
        }
    }
});

Here item means the model in the collection. Hope this helps.




回答2:


You'll want to override the buildItemView method:

buildItemView: function(item, ItemViewType, itemViewOptions){
  var options = _.extend({model: item}, itemViewOptions);

  build a custom view
  if (item instanceOf ModelA) {
      return new ItemViewA(options);
  }
  // else as needed

  // default view
  return new ItemViewType(options);
}


来源:https://stackoverflow.com/questions/18684567/backbone-marionette-different-composite-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!