在 Backbone 中查找模型.js按 cid 而不是 id 收集

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

本文关键字:id 收集 cid Backbone 查找 模型 js      更新时间:2023-09-26

我可以使用 Collection.get(id) 在 Backbone.js 集合中查找尚未保存到服务器的模型吗?

从文档中看,.get 似乎应该通过其 id 或 cid 找到一个模型。 但是,collection.get(cid)找不到模型,而这确实collection.find(function(model) {return model.cid===cid; })。 大概我忽略了一些基本的东西。

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 0.9.9 中

(参见 changelog),他们删除了 .getByCid() 方法并将该功能直接折叠到 .get() 中——如果你使用低于 0.9.9,你可以使用 .getByCid() 方法;我认为他们已经从文档中删除了它,以反映库的最新状态。

编辑:

有关更多详细信息@Ferdinand请参阅下面的 Prantl 评论,但将cid作为对象文本的属性传递将完成您在此处查找的内容:.get({ cid: "xxx" }) 。 对于任何困惑,我深表歉意。