2012-11-05 31 views
3

我使用骨幹集合從服務器獲取mongodb集合。由於id存儲爲'_id',因此我使用idAttribute將其映射爲'_id'。獲取集合時未設置idAttribute

(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」身份證',從意味着this.model.isNew()對於從服務器獲取的所有記錄,視圖返回「true」。因此我不能刪除也不能向服務器放入一個條目。

但是如果我使用的原型是這樣(的PlaceModel定義裏面,而不是)設置idAttribute:

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

然後正確idAttribute映射到「_id」,和一切正常。可能發生了什麼?

回答

7

當你這樣說:

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

這是一樣的,或多或少的,因爲說這句話的:

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

你不設定集 「類」 的model財產,您只需創建一個包含一個模型的集合(一個普通的Backbone.Model實例,而不是一個PlaceModel),該模型的model屬性的值爲PlaceModel

所以,鑑於這一切,該集合不知道其模型應該有idAttribute: "_id"或甚至它的模型應該是PlaceModel。當您創建PlaceCollection而不是創建place時,您希望看到model

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

var place = new PlaceCollection;