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