简体   繁体   English

骨干集合通过其ID获取模型

[英]Backbone Collection get Model by it's ID

I've problems getting a single Model by its ID even though I set the idAttribute in the coresponding Model. 即使在coresponding模型中设置了idAttribute,我也无法通过其ID获得单个模型。

A Collection looks like this: 集合看起来像这样:

[
    {
        "_account": "51dc04dbe4e643043d000001",
        "name": "test.png",
        "type": "image/png",
        "_id": "51ff833f0342ee0000000001",
        "added": "2013-08-05T10:49:35.737Z"
    }
]

// Inside the Model I defined idAttribute
FileModel = Backbone.Model.extend({

idAttribute : "_id",
urlRoot : "/api/file"

[...]

}
// The collection contain each of the Model items
// but if I try to get a single model item  by id:

Collection.get("51ff833f0342ee0000000001") -> the result is undefined

I cant figure out why and the solution from Backbone.Collection get model by id was not the key to solve the problem. 我想不通为什么,从Backbone.Collection通过id获取模型的解决方案不是解决问题的关键。

In order to retrieve a model by a custom id you need to specify on the model it's idAttribute and you need to specify the collection's model property to use your model. 为了通过自定义ID检索模型,您需要在模型上指定其idAttribute,并且需要指定集合的model属性以使用模型。 Normally it's enough to set this in your collection where you declare it's properties 通常,在声明其属性的集合中设置它就足够了

var MyCollection = Backbone.Collection.extend({
  model: FileModel,
  ...
})

However depending on how you have your JavaScript laid out (and therefore how the JavaScript is evaluated by the browser) it is possible at the time the model: FileModel statement is read it is still undefined. 但是,取决于您的JavaScript布局方式(以及浏览器如何评估JavaScript),有可能在读取model: FileModel语句时仍未定义。 To get around this you can move the assignment of the property to the initialize/constructor of your collection. 为了解决这个问题,您可以将属性的分配移动到集合的初始化/构造函数中。

For example 例如

var MyCollection = Backbone.Collection.extend({

        initialize: function () {
            this.model = FileModel;
        }
    ...
});

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

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