Toms Mikoss
Toms Mikoss

Reputation: 9437

Backbone.Marionette - CollectionView with different ItemView classes

I'm looking to re-build a vanilla Backbone app into a Backbone.Marionette based one. However, one of the existing views is giving me headache - a collection of different sub-views.

For exampe, the server returns a list that contains 100 entries, 50 items of type A, 49 items of type B and one C. Those then get grouped by type at client-side, and rendered as one GroupView that has the A entries, one GroupView for B entries, and one EntryView for C. GroupViews then can be expanded to show the individual EntryViews.

I can build a collection that contains three models - two Group models (with their respective Entry models inside), and one plain Entry model. But how do I tell the collection view to use GroupView to render Group models, and EntryView for Entry models?

Upvotes: 2

Views: 96

Answers (1)

joews
joews

Reputation: 30330

You can override CollectionView.getChildView to decide which child view type to use for each model in the parent collection.

Assuming your Model types have a method called isGroup that returns a truthy value if the model is a Group or falsy otherwise:

var HeterogenousCollectionView = Marionette.CollectionView.extend({

  getChildView: function(model) { 
    if(model.isGroup()) {
      return GroupView;
    } else {
      return EntryView;
    }
  }

})

See the Marionette docs for more detail. I also recommend browsing the annotated source code - it's concise enough to get a good feel for how Marionette view types work.

Upvotes: 4

Related Questions