Backbone Collection通过它的ID获取Model

时间:2013-08-05 13:39:01

标签: javascript backbone.js

即使我在相应的模型中设置idAttribute,我也无法通过其ID获取单个模型。

集合看起来像这样:

[
    {
        "_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

我无法弄清楚原因,Backbone.Collection get model by id的解决方案不是解决问题的关键。

1 个答案:

答案 0 :(得分:1)

要通过自定义ID 检索模型,您需要在模型上指定它是idAttribute,并且您需要指定集合的​​model属性才能使用您的模型。通常情况下,在您声明它的属性

的集合中设置它就足够了
var MyCollection = Backbone.Collection.extend({
  model: FileModel,
  ...
})

但是,根据您的JavaScript布局方式(以及浏览器如何评估JavaScript),可能会在读取model: FileModel语句时仍未定义。要解决此问题,您可以将属性的赋值移动到集合的初始化/构造函数中。

例如

var MyCollection = Backbone.Collection.extend({

        initialize: function () {
            this.model = FileModel;
        }
    ...
});
相关问题