pro*_*ype 13 javascript backbone.js backbone.js-collections
对于尚未保存到服务器的模型,我可以使用Collection.get(id)通过cid在Backbone.js集合中查找模型吗?
从文档中看,似乎.get应该通过id或cid找到一个模型.但是,collection.get(cid)没有找到模型,而这确实如此collection.find(function(model) {return model.cid===cid; }).据推测,我忽略了一些基本的东西.
var Element = Backbone.Model.extend({});
var Elements = Backbone.Collection.extend({ model: Element });
var elements = new Elements(), el, cids = [];
for (var i=0; i<4; i++) {
el = new Element({name: "element"+i})
elements.add(el);
cids.push(el.cid);
}
console.log(cids);
el1 = elements.get(cids[0]);
console.log(el1); // undefined
el1a = elements.find(function(model) { return model.cid === cids[0]; });
console.log(el1a); // success
Run Code Online (Sandbox Code Playgroud)
Bry*_*n A 24
在主干0.9.9(参见更改日志)中,他们删除了该.getByCid()方法并将该功能直接折叠到.get()- 如果您使用的是0.9.9以下,则可以使用该.getByCid()方法; 我认为他们已经从文档中删除它以反映库的最新状态.
编辑:
有关更多详细信息,请参阅下面的@Ferdinand Prantl的评论,但是将cid对象文字作为属性传递将完成您在此处寻找的内容:.get({ cid: "xxx" }).我为任何困惑道歉.