2013-08-02 19 views
8

我想知道如何/如何一個CompositeView可以將數據傳遞到其定義的itemView。示例(精簡)代碼:Backbone.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; 
    } 
}); 

我正在使用這兩個呈現html表。 #table-row-template有一些呈現邏輯來支持不同類型的「列」。這允許我對不同類型的集合/模型使用相同的視圖(只要它們遵循API)。到目前爲止,它工作得很好!

但是,正如您在上面看到的,每次「行」都會調用每次獲得相同的「列」數據,當時我只是想把它傳遞一次,然後用於所有數據。

建議?

謝謝!

回答

13

可以使用itemViewOptions無論是作爲一個對象或一個函數

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

,然後接收選項有:

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

(*注意:ItemView控件itemV iewContaineritemViewOptions在版本2中變更爲childViewchildViewContainerchildViewOptions)。

+1

讚賞。非常感謝。文檔可以做更新。 – starmonkey

+4

n.b. Marionette v2將'item *'改爲'child *' – alxndr

相關問題