2013-03-20 11 views
6

私はCollectionViewMarionette CollectionViewでは、(コレクション内の)モデルのインデックスをどのようにItemViewに渡すことができますか?

class MyCollectionView extends Backbone.Marionette.CollectionView 
    itemView: MyItemView 

    itemViewOptions: -> 
    { 
     indexInCollection: ? 
    } 

を持っていると私はMyItemViewは、そのモデルがである、コレクション内のどの指標で知りたいです。私が思う

は、MyItemViewに、私は

@model.collection.indexOf(@model) 

を経由して、それを見つけることができますしかし、いくつかの内部マリオネットメカニズムを使用して、私のマリオネットCollectionViewからMyItemViewに直接にそれを渡す方法はありますか?このインデックスは既にどこかに公開されていますか?

答えて

12

itemViewOptionsは、機能としてセットアップされたとき、itemまたはmodelパラメータを受け取ります。インデックスを検索し、これを使用します。


class MyCollectionView extends Backbone.Marionette.CollectionView 
    itemView: MyItemView 

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

完璧なああのためのマリオネットのマニュアルに記載されている - 私のようなエレガントな何かがあったに違いありません知っていましたこの。ありがとうDerick。 – Joerg

+0

woah cool私はこれを知らなかった! –

+0

ここで素晴らしい解決策 – jmeas

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 
     } 

この方法で、テンプレートの "index"変数にアクセスできます。

+1

'serializeData'をオーバーライドし、そこからテンプレートにインデックスvarを公開するほうが良いでしょう。 – vaughan

6

マリオネットは、あなたがchildViewOptions機能でそれを行うことができます2.0.0以来:

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

としてはchildViewOptions

関連する問題