获取集合时未设置idAttribute

时间:2012-11-05 01:53:09

标签: backbone.js

我使用骨干集合从服务器获取mongodb集合。由于id存储为'_id',我使用idAttribute将其映射到'_id'。

(function(){
  var PlaceModel = Backbone.Model.extend({
    idAttribute: "_id",
  });
  var PlaceCollection = Backbone.Collection.extend({
    url: "http://localhost:9090/places",
    initialize: function(options){
      var that = this;
      this.fetch({
        success: function(){
          console.log("Success!", that.toJSON());
        },
        error: function(){
          console.log("Error");
        }
      });
    }
  });

  var place = new PlaceCollection({model:PlaceModel});

}()); 

但是稍后当我尝试在删除条目时访问模型的'idAttribute'时,它返回'id'而不是'_id',这意味着来自视图的this.model.isNew()返回'true '对于从服务器获取的所有记录。因此,我不能删除也不能输入服务器。

但是如果我使用这样的原型设置idAttribute(而不是在PlaceModel定义中):

Backbone.Model.prototype.idAttribute = "_id";

然后它正确地将idAttribute映射到'_id',一切正常。可能会发生什么?

1 个答案:

答案 0 :(得分:7)

当你这样说时:

var place = new PlaceCollection({model:PlaceModel});

这或多或少都是这样说的:

var o     = new Backbone.Model({ model: PlaceModel });
var place = new PlaceCollection([ o ]);

您没有设置集合“class”的model属性,您只需创建一个包含一个模型的集合(一个普通的Backbone.Model实例,而不是PlaceModel })该模型的model属性值为PlaceModel

所以,尽管如此,该集合并不知道它的模型应该具有idAttribute: "_id",或者甚至认为它的模型应该是PlaceModel。您希望在创建model时看到PlaceCollection,而不是在创建place时看到:

var PlaceCollection = Backbone.Collection.extend({
  url: "http://localhost:9090/places",
  model: PlaceModel,
  //...
});

var place = new PlaceCollection;