Backbone.Collection 通过 id 获取模型 [英] Backbone.Collection get model by id
问题描述
我有一个从服务器获取模型的集合.
I have a collection that fetches models from server.
这行得通,现在我想通过 MyCollection.at(0)
的 id 获取模型,然后我得到:
This works, now I want to grab a model by its id with MyCollection.at(0)
and I get:
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 获取模型,我会得到:
If I try to get the model by its id i get:
MyCollection.get("50ef7a63b2a53d17fe000001")
=> undefined
MyColleciton.get({_id:"50ef7a63b2a53d17fe000001"})
=> undefined
MyCollection.get({'_id':"50ef7a63b2a53d17fe000001"})
=> undefined
我不明白 - 文档清楚地说明 .get()
方法将返回模型,如果该集合中存在具有给定 id 的模型.
I don't get that - the docs say clearly that the .get()
method will return the model if a model with the given id exists in that collection.
推荐答案
Model.idAttribute
在模型上?
var Model = Backbone.Model.extend({
idAttribute:"_id"
});
默认情况下,Backbone 期望 id 属性被称为 id.当设置了 idAttribute
时,Backbone 标准化了 id 的处理,以便 model.id
始终可用,即使 id 属性被称为其他东西.原始 id 属性在模型的 attributes
哈希中可用,因此可以通过 get
方法获得.所以:
By default Backbone expects the id property be called id. When the idAttribute
has been set, Backbone standardizes handling of ids so that model.id
is always available, even if the id property is called something else. The original id property is available in the Model's attributes
hash, and as such via the get
methd. So:
model.id === model.get('_id') // -> true
这篇关于Backbone.Collection 通过 id 获取模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!