2013-07-17 30 views
1

我正在開發應用程序,當我創建一個組時,保存功能很好地工作,模型被添加到集合中,並保存到數據庫,但是如果我然後編輯我剛剛創建的組,當我點擊保存時,創建新的模型(和POST請求),而不是正在編輯的數據以及PUT請求被觸發。這裏是我的保存功能 - 是否有什麼理由在編輯現有模型時沒有發出PUT請求?模型創建新行而不是編輯

GroupModalHeaderView.prototype.save = function(e) { 
    var $collection, $this; 
    if (e) { 
    e.preventDefault(); 
    } 

    $this = this; 
    if (this.$("#group-name").val() !== "") { 
    $collection = this.collection; 
    if (this.model.isNew()) { 
     this.collection.add(this.model); 
    } 
    return this.model.save({ name: this.$("#group-name").val()}, { 
     async: false, 
     wait: true, 
     success: function() { 
     var modelID = $this.model.get('id'); 

     return this.modal = new app.GroupModalView({ 
      model: $this.collection.get(modelID), 
      collection: $this.collection 
     }); 
     } 
    }); 
    } 

}; 

這是我的模型違約,

Group.prototype.defaults = { 
    user_id: "", 
    name: "New Group", 
    email: "", 
    url: "", 
    telephone: "", 
    mobile: "", 
    fax: "", 
    people: "" 
}; 

這裏是this.model的執行console.log被保存在它之前,

Group {cid: "c116", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…} 
     _changing: false 
     _events: Object 
     _pending: false 
     _previousAttributes: Object 
     email: "" 
     fax: "" 
     mobile: "" 
     name: "New Group" 
     people: "" 
     telephone: "" 
     url: "" 
     user_id: "" 
     wait: true 
     __proto__: Object 
     attributes: Object 
     changed: Object 
     cid: "c116" 
     collection: GroupCollection 
     id: 189 
     __proto__: ctor 

回答

1

原因是Backbone.js的射擊POST請求而不是PUT是因爲您的模型沒有與之相關聯的唯一標識符id。如果沒有id屬性與您的模型相關聯,那麼Ba ckbone.js將總是觸發POST請求以將新條目保存到數據庫。

從骨幹網的網站:

保存model.save([屬性],[選項])......如果模型是否新款,在

節省將是一個 「創造」(HTTP POST ),如果模型已經存在於 服務器上,保存將是一個「更新」(HTTP PUT)。

閱讀this SO question瞭解更多信息。

+0

謝謝你能看看我的編輯?有問題嗎? – Udders

+0

您需要在模型中設置'id',然後發出保存請求 –

+0

但是,如果我在成功回調中執行console.log($ this.model.get(「id」),則可以看到模型ID ? – Udders

相關問題