2013-01-13 88 views
14

我有一個從服務器獲取模型的集合。Backbone.Collection通過編號獲取模型

這個工作,現在我要抓住它的ID的模型MyCollection.at(0)和獲取:

child 
_changes: Array[0] 
_changing: false 
_currentAttributes: Object 
_events: Object 
_hasComputed: true 
_pending: false 
_previousAttributes: Object 
attributes: Object 
_id: "50ef7a63b2a53d17fe000001" 
author_name: "author name" 
bookmark: "" 
info: "bookmark description" 
__proto__: Object 
changed: Object 
cid: "c26" 
collection: child 
view: child 
__proto__: Surrogate 

如果我試圖讓通過其ID的模式,我得到:

MyCollection.get("50ef7a63b2a53d17fe000001") 
=> undefined 

MyColleciton.get({_id:"50ef7a63b2a53d17fe000001"}) 
=> undefined 

MyCollection.get({'_id':"50ef7a63b2a53d17fe000001"}) 
=> undefined 

我不明白 - 文檔中明確指出,如果具有給定標識的模型存在於該集合中,則.get()方法將返回該模型。

回答

20

您是否在模型上設置了Model.idAttribute

var Model = Backbone.Model.extend({ 
    idAttribute:"_id" 
}); 

默認情況下,Backbone希望id屬性被稱爲id。當idAttribute已設置時,Backbone將標準化處理標識符,以便model.id始終可用,即使id屬性被稱爲其他東西。模型的attributes散列中提供了原始的id屬性,並通過get方法提供。所以:

model.id === model.get('_id') // -> true 
+1

你是對的! (在這裏插入面部手掌)我不知道從文檔中得到這個,並認爲_id = id是默認值。謝謝 ;-) – Inoperable

3

您可以使用模型的cid(客戶端ID)屬性作爲MyCollection.get()的參數,該值保證在創建時存在。文件似乎認爲這將起作用,請參閱http://backbonejs.org/#Collection-get

+0

我得到的ID不是CID,我想使用ID而不是CID。 – Inoperable

+0

它們都唯一標識模型。 –

+3

我明白了,但我確實想知道爲什麼我不能通過id訪問模型,正如我所說 - cid不是問題。 – Inoperable