I have a CollectionView
class MyCollectionView extends Backbone.Marionette.CollectionView
itemView: MyItemView
itemViewOptions: ->
{
indexInCollection: ?
}
And I want MyItemView to know at which index in the collection its model is at.
I suppose, in the MyItemView, I can find it out via
@model.collection.indexOf(@model)
But is there a way to pass it in directly into MyItemView from my Marionette CollectionView, using some internal Marionette mechanism? Is this index exposed somewhere already?
the itemViewOptions
, when set up as a function, receives an item
or model
parameter. Use this to find the index:
class MyCollectionView extends Backbone.Marionette.CollectionView
itemView: MyItemView
itemViewOptions: (model) ->
{
indexInCollection: this.collection.indexOf(model)
}
Since Marionette 2.0.0 you can do it with a childViewOptions function:
var CollectionView = Marionette.CollectionView.extend({
childViewOptions: function(model, index) {
// do some calculations based on the model
return {
foo: "bar",
childIndex: index
}
}
});
As explained in the Marionette documentation for childViewOptions
Just adding to the previous answer, if you want to use one of the options in one of your view templates, you can simply do it like this:
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
}
This way, you can get access to the "index" variable in your template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With