Backbone.Marionette: Pass data down through a CompositeView to its itemView?
Asked Answered
Y

1

9

I'm wondering if/how a CompositeView can pass data down into its defined itemView. Example (reduced) 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'm using the two to render a html table. #table-row-template has some render logic for supporting different types of "columns". This allows me to use the same views for different types of Collections/Models (as long as they follow the API). So far, it's working pretty well!

However, as you can see above, each "row" makes a call to get the same "columns" data every time, when really I just wanted to pass that on down once, and use for all.

Recommendations?

Thanks!

Yellowlegs answered 2/8, 2013 at 0:31 Comment(0)
B
14

You can use itemViewOptions either as an object or 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 receive the options with:

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).

Brachyuran answered 2/8, 2013 at 3:2 Comment(1)
n.b. that Marionette v2 changed item* to child*Demeter

© 2022 - 2024 — McMap. All rights reserved.