Backbone.Collection通过id获取模型

Ino*_*ble 14 javascript backbone.js

我有一个从服务器获取模型的集合.

这是有效的,现在我想通过它的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
Run Code Online (Sandbox Code Playgroud)

如果我尝试通过其ID得到模型我得到:

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

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

MyCollection.get({'_id':"50ef7a63b2a53d17fe000001"})
=> undefined
Run Code Online (Sandbox Code Playgroud)

我不明白 - 文档清楚地说明.get()如果该集合中存在具有给定id的模型,该方法将返回模型.

jev*_*lio 20

你有没有设置Model.idAttribute模型?

var Model = Backbone.Model.extend({
    idAttribute:"_id"
});
Run Code Online (Sandbox Code Playgroud)

默认情况下,Backbone期望id属性被称为id.当idAttribute已定,骨干IDS进行标准化处理,以便model.id始终可用,即使id属性被称为别的东西.原始id属性在Model的attributes哈希中可用,因此通过getmethd.所以:

model.id === model.get('_id') // -> true
Run Code Online (Sandbox Code Playgroud)