Javascript Backbone.Collection 通过 id 获取模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14299992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:19:13  来源:igfitidea点击:

Backbone.Collection get model by id

javascriptbackbone.js

提问by Inoperable

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.

我不明白 - 文档明确指出,.get()如果该集合中存在具有给定 id 的模型,则该方法将返回模型。

回答by jevakallio

Have you set Model.idAttributeon the Model?

Model.idAttribute在模型上设置了吗?

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

By default Backbone expects the id property be called id. When the idAttributehas been set, Backbone standardizes handling of ids so that model.idis always available, even if the id property is called something else. The original id property is available in the Model's attributeshash, and as such via the getmethd. So:

默认情况下,Backbone 期望 id 属性被称为 id。当idAttribute已定,骨干标准化处理的ID,这样model.id始终可用,即使id属性被称为别的东西。原始 id 属性在模型的attributes哈希中可用,因此可以通过方法获得get。所以:

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

回答by Rafe Kettler

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. The documentation seems to think that will work, see http://backbonejs.org/#Collection-get.

您可以使用模型的cid(客户端 ID)属性作为 的参数MyCollection.get(),保证从创建开始就存在。文档似乎认为这会起作用,请参阅http://backbonejs.org/#Collection-get