2013-01-13 92 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