2013-03-20 32 views
6

我有一個的CollectionView在Marionette CollectionView中,如何將模型的索引(集合中)傳遞給ItemView?

class MyCollectionView extends Backbone.Marionette.CollectionView 
    itemView: MyItemView 

    itemViewOptions: -> 
    { 
     indexInCollection: ? 
    } 

而且我想MyItemView知道在該指數集合在它的模型在。

我想,在MyItemView,我可以通過

@model.collection.indexOf(@model) 

發現它不過是有辦法在通過它直接進入從我的木偶的CollectionView MyItemView,利用一些內部機制的木偶?這個索引是否已經暴露在某個地方?

回答

12

itemViewOptions當設置爲功能時,接收itemmodel參數。使用此找到索引:


class MyCollectionView extends Backbone.Marionette.CollectionView 
    itemView: MyItemView 

    itemViewOptions: (model) -> 
    { 
     indexInCollection: this.collection.indexOf(model) 
    } 
+0

完美啊 - 我知道一定有喜歡的事,優雅這個。謝謝Derick。 – Joerg 2013-03-21 06:23:54

+0

我很酷,我還沒有意識到這一點! – 2013-03-21 13:29:43

+0

偉大的解決方案 – jmeas 2013-11-22 21:28:05

1

只是增加了前面的答案,如果你想使用的選項之一的視圖模板之一,你可以簡單地做這樣的:

class Run.Question extends Backbone.Marionette.ItemView 
    template: "mock/run/question" 
    initialize: -> 
     @model = @model.set index: @options.index 

class Run.Content extends Backbone.Marionette.CompositeView 
    template: "mock/run/content" 
    itemView: Run.Question 
    itemViewContainer: "div.data-box" 
    itemViewOptions: (model) -> 
     { 
      index: @collection.indexOf(model) + 1 
     } 

這樣,您可以訪問模板中的「索引」變量。

+1

可能更適合覆蓋'serializeData'並將索引var暴露給模板。 – vaughan 2014-07-16 13:15:37

6

由於木偶2.0.0您可以用childViewOptions做功能:

var CollectionView = Marionette.CollectionView.extend({ 
    childViewOptions: function(model, index) { 
    // do some calculations based on the model 
    return { 
     foo: "bar", 
     childIndex: index 
    } 
    } 
}); 

由於木偶文檔中解釋了childViewOptions

相關問題