简体   繁体   English

Backbone.Collection通过id获取模型

[英]Backbone.Collection get model by id

I have a collection that fetches models from server. 我有一个从服务器获取模型的集合。

This works, now I want to grab a model by its id with MyCollection.at(0) and I get: 这工作,现在我想通过其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

If I try to get the model by its id i get: 如果我尝试通过其ID得到模型我得到:

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

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

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

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

Have you set Model.idAttribute on the Model? 你在Model上设置了Model.idAttribute吗?

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

By default Backbone expects the id property be called id. 默认情况下,Backbone期望id属性被称为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. 设置idAttribute ,Backbone标准化了对id的处理,使得model.id始终可用,即使id属性被调用。 The original id property is available in the Model's attributes hash, and as such via the get methd. 原始id属性在Model的attributes哈希中可用,因此通过get methd。 So: 所以:

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

You can use the cid (client-side ID) attribute of the model as an argument to MyCollection.get() , which is guaranteed to exist from creation on. 您可以使用模型的cid (客户端ID)属性作为MyCollection.get()的参数,该参数保证在创建时存在。 The documentation seems to think that will work, see http://backbonejs.org/#Collection-get . 文档似乎认为可行,请参阅http://backbonejs.org/#Collection-get

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM