简体   繁体   English

通过cid而不是id在Backbone.js集合中查找模型

[英]Find model in Backbone.js collection by cid rather than id

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? 对于尚未保存到服务器的模型,我可以使用Collection.get(id)通过cid在Backbone.js集合中查找模型吗?

From the documentation, it seems like .get should find a model by either its id or cid. 从文档中看,似乎.get应该通过id或cid找到一个模型。 However, collection.get(cid) doesn't find the model, whereas this does, collection.find(function(model) {return model.cid===cid; }) . 但是, collection.get(cid)找不到模型,而这就是, collection.find(function(model) {return model.cid===cid; }) Presumably I'm overlooking something basic. 据推测,我忽略了一些基本的东西。

jsFiddle for example below jsFiddle例如下面

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 Backbone.js - id vs idAttribute vs cid

In 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; 在主干0.9.9( 参见changelog )中,他们删除了.getByCid()方法并将该功能直接折叠到.get() - 如果你使用的是0.9.9以下,你可以使用.getByCid()方法; 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" }) . 有关更多详细信息,请参阅下面的@Ferdinand Prantl的注释,但将cid作为对象文字的属性传递将完成您在此处寻找的内容: .get({ cid: "xxx" }) My apologies for any confusion. 我为任何困惑道歉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM