javascript 通过 cid 而不是 id 在 Backbone.js 集合中查找模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14525258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find model in Backbone.js collection by cid rather than id
提问by prototype
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. 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.
从文档中,似乎 .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
回答by Bryan A
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; I think they've since removed it from the docs to reflect the most current state of the library.
在主干 0.9.9(参见变更日志)中,他们删除了该.getByCid()
方法并将该功能直接折叠到.get()
- 如果您使用低于 0.9.9,则可以使用该.getByCid()
方法;我认为他们已经从文档中删除了它以反映库的最新状态。
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.
见@Ferdinand Prantl的评论以下更多的细节,不过将cid
作为对象文本的属性将完成你在找什么在这里:.get({ cid: "xxx" })
。对于任何混淆,我深表歉意。