admin管理员组文章数量:1202372
Can I use Collection.get(id) to find a model within a Backbone.js collection by cid, for a model not yet saved to the server?
From the documentation, it seems like .get should find a model by either its id or cid. However, collection.get(cid)
doesn't find the model, whereas this does, collection.find(function(model) {return model.cid===cid; })
. Presumably I'm overlooking something basic.
jsFiddle for example below
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
Backbone.js - id vs idAttribute vs cid
Can I use Collection.get(id) to find a model within a Backbone.js collection by cid, for a model not yet saved to the server?
From the documentation, it seems like .get should find a model by either its id or cid. However, collection.get(cid)
doesn't find the model, whereas this does, collection.find(function(model) {return model.cid===cid; })
. Presumably I'm overlooking something basic.
jsFiddle for example below
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
Backbone.js - id vs idAttribute vs cid
Share Improve this question edited May 23, 2017 at 12:00 CommunityBot 11 silver badge asked Jan 25, 2013 at 15:51 prototypeprototype 7,97015 gold badges65 silver badges99 bronze badges1 Answer
Reset to default 24In backbone 0.9.9 (see changelog), they removed the .getByCid()
method and folded that functionality directly into .get()
-- if you're using below 0.9.9, you can use the .getByCid()
method; I think they've since removed it from the docs to reflect the most current state of the library.
Edit:
See @Ferdinand Prantl's comment below for more detail, but passing the cid
as the property of an object literal will accomplish what you're looking for here: .get({ cid: "xxx" })
. My apologies for any confusion.
本文标签: javascriptFind model in Backbonejs collection by cid rather than idStack Overflow
版权声明:本文标题:javascript - Find model in Backbone.js collection by cid rather than id - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738598606a2101934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论