Backbone.Marionette:通过CompositeView将数据传递到itemView?

sta*_*key 9 marionette

我想知道CompositeView是否/如何将数据传递到其定义的itemView.示例(简化)代码:

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

我正在使用这两个来呈现一个html表.#table-row-template有一些渲染逻辑,用于支持不同类型的"列".这允许我对不同类型的集合/模型使用相同的视图(只要它们遵循API).到目前为止,它运作良好!

但是,正如您在上面所看到的,每次"行"都会调用以获取相同的"列"数据,而实际上我只想将其传递一次,然后用于所有数据.

建议?

谢谢!

小智 14

您可以将itemViewOptions其用作对象或函数

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

要么

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

然后收到以下选项:

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

(*注意ItemView控件,itemViewContaineritemViewOptions 2版本改变为childView,childViewContainerchildViewOptions).

  • nb,Marionette v2将`item*'改为`child*` (4认同)