3

我正在使用骨干集合从服务器获取 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”,一切正常。可能会发生什么?

4

1 回答 1

7

当你这样说时:

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

这或多或少是一样的,就像这样说:

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

您没有设置集合“类”的model属性,您只是创建了一个包含一个模型的集合(一个普通Backbone.Model实例,而不是 a PlaceModel),并且该模型具有一个modelvalue 属性PlaceModel

因此,鉴于所有这些,该集合不知道它的模型应该有idAttribute: "_id",甚至不知道它的模型应该是PlaceModel. 您想查看model创建时间PlaceCollection,而不是创建place时间:

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

var place = new PlaceCollection;
于 2012-11-05T04:21:41.657 回答