Backbone.Marionette: pass data via CompositeView to itemView element?

I am wondering how and how a CompositeView can pass data to its specific itemView. Example (abbreviated) code:

var TableView = Backbone.Marionette.CompositeView.extend({ template: '#table-template', itemView: TableRowView, itemViewContainer: 'tbody', }); var TableRowView = Backbone.Marionette.ItemView.extend({ tagName: 'tr', template: '#table-row-template', serializeData: function () { var data = { model: this.model, // FIXME This should really only be called once. Pass into TableView, and down into TableRowView? // That way, getDisplayColumns can be moved to the collection as well, where it makes more sense for it to belong. columns: this.model.getDisplayColumns() }; return data; } }); 

I use these two to display an html table. # table-row-template has some visualization scheme to support different types of columns. This allows me to use the same views for different types of collections / models (provided that they follow the API). So far it works very well!

However, as you can see above, each "row" makes a call to get the same "columns" of data every time I just wanted to pass it once and use it for everyone.

Recommendations

Thanks!

+8
marionette
source share
1 answer

You can use itemViewOptions either as an object or as a function

 var TableView = Backbone.Marionette.CompositeView.extend({ template: '#table-template', itemView: TableRowView, itemViewContainer: 'tbody', itemViewOptions: { columns: SOMEOBJECTORVALUE } }); 

OR

 var TableView = Backbone.Marionette.CompositeView.extend({ template: '#table-template', itemView: TableRowView, itemViewContainer: 'tbody', itemViewOptions: function(model,index){ return{ columns: SOMEOBJECTORVALUE } } }); 

and then get the following options:

 var TableRowView = Backbone.Marionette.ItemView.extend({ tagName: 'tr', template: '#table-row-template', initialize: function(options){ this.columns = options.columns; } }); 

(* Note that itemView , itemViewContainer and itemViewOptions are changed in version 2 to childView , childViewContainer and childViewOptions ).

+13
source share

All Articles