Backbone Marionette different composite views

2019-05-16 12:35发布

问题:

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);
}