簡體   English   中英

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

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

對於尚未保存到服務器的模型,我可以使用Collection.get(id)通過cid在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

在主干0.9.9( 參見changelog )中,他們刪除了.getByCid()方法並將該功能直接折疊到.get() - 如果你使用的是0.9.9以下,你可以使用.getByCid()方法; 我認為他們已經從文檔中刪除它以反映庫的最新狀態。

編輯:

有關更多詳細信息,請參閱下面的@Ferdinand Prantl的注釋,但將cid作為對象文字的屬性傳遞將完成您在此處尋找的內容: .get({ cid: "xxx" }) 我為任何困惑道歉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM