Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Marionette CollectionView, how can I pass the index of the model (in the collection) to the ItemView?

Tags:

marionette

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?

like image 423
Joerg Avatar asked Mar 20 '13 05:03

Joerg


3 Answers

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)
    }
like image 113
Derick Bailey Avatar answered Nov 17 '22 22:11

Derick Bailey


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

like image 40
DiegoG Avatar answered Nov 17 '22 21:11

DiegoG


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.

like image 1
Gerson Azevedo Avatar answered Nov 17 '22 23:11

Gerson Azevedo