开发者

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

Ho开发者_开发知识库w can I build a ViewB of ModelB with a button which, when clicked, changes an attribute on the next ModelB instance in the collection?


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.


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 });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜