Skip to content Skip to sidebar Skip to footer

Backbone.js: Button In View That Affects A Different Model In Collection

I'm just getting going with backbone.js. So far, I'm really liking it. I have something like this: ModelA ModelB ViewA ViewB ModelA holds a collection of ModelB How can I build

Solution 1:

var col = this.model.collection;
var nextModel = col.at( col.indexOf(this.model) + 1)
if(nextModel) nextModel.set({whatevar});

You do not need to keep track of the parent collection, backbone does it for you. You should check if you are at the end of the collection also.

Solution 2:

I think I figured something out. I'll share to see what others think so that others can benefit.

I simply pass in a reference to the parent collection to each model in the collection.

Inside my collection, when adding a new instance:

var newModelBInstance = new ModelB( { id: "xxx", ParentCollection: this } );

And then, inside my ModelB view:

this.model.get("ParentCollection").at(this.model.sortValue + 1).set({ myAttr: false });

Post a Comment for "Backbone.js: Button In View That Affects A Different Model In Collection"