This should be easy, as a model in a collection can easily get the information you need. You'll need to create a "view model" wrapper around your model so that you can grab the extra info that you want.
var createViewModel(model){
// inherit from the original model
var vm = Object.create(model);
// override the original `toJSON` method
vm.toJSON = function(){
var json = model.toJSON();
// add the index
json.index = model.collection.indexOf(model);
return json;
}
return vm;
}
This view model will be used by your itemView, directly.
MyItemView = Backbone.Marionette.ItemView.extend({
template: "#my-item-view-template",
initialize: function(){
// replace the model with the the view model
this.model = createViewModel(this.model);
}
});
MyCollectionView = Backbone.Marionette.CollectionView({
itemView: MyItemView
});
And that's it.
When you pass your collection in to the MyCollectionView
constructor and render the collection view, a new view model will be created for each itemView instance, at the time the itemView is instantiated. The template can render the index
from the model now.
The view model inherits from the original model directly, so all of the methods and attributes are still available. Overriding the toJSON
method allows you to get the original json out of the original model, and then augment it with whatever data you need. Your original model is never modified, but the model that the item view is using has the data you need.