2011-12-15 72 views
1

我的問題是如何更新集合中的模型?這是我正在做的。在頁面加載時,我獲取聯繫人列表。在一個視圖中,我將這些聯繫人列在無序列表中。每個聯繫人都是可點擊的,這會將您帶到編輯表單。一旦你改變了聯繫人,你就可以保存聯繫人。這將帶你到一個方法,將修改後的模型保存回集合。你會如何做到這一點?在骨幹文檔中沒有更新方法(或者至少我沒有看到它)。我創建了一個這樣做的方式,但我不確定它是否是首選的Backbone方式。那就是:更新集合中的模型

 updatePlan : function() 
     { 
      //unique ID of the model 
      var id = $('input[ name=id ]').val(); 
      //remove the old model from the collection 
      this.collection.remove(this.model); 
      //add the updated model to the collection 
      this.collection.add(this.model);    

     } 

你會覺得會有這樣的功能:

 updatePlan : function() 
     { 
      this.collection.update(this.model); 

     } 

感謝您的幫助

回答

0

你可以有你的觀點,即允許用戶編輯聯繫人爲你更新模型。並且,由於模型通過引用傳遞,它也將在它所屬的集合中進行更新。

下面是一個例子。

EditView = Backbone.View.extend({ 
    events: { 
    'change #name': 'nameChanged', 
    'change #age': 'ageChanged' 
    }, 
    render: function() { 
    //render code 
    }, 
    nameChanged: function() { 
    var nameValue = this.$('#name').val(); 
    this.model.set({ Name : nameValue }); 
    }, 
    ageChanged: function() { 
    var ageValue = this.$('#age').val(); 
    this.model.set({ Age : ageValue }); 
    } 
} 

然後當你創建的編輯視圖,您所選擇的模型從收集

selectedContact = contactCollection.at(0); 
var editView = new EditView({ model: contact }); 
$('#editDiv').html(editView.render().el); 

唯一剩下要做的傳遞是將模型保存到服務器,當用戶點擊保存按鈕。

$('#saveButton').click(function() { 
    selectedContact.save(); 
}); 
0

我同意保羅的觀點,你應該有一個視圖爲你的收藏,一個視圖爲你的模型。 該模型的視圖允許您編輯模型,保存應正確傳播。

然而,說你似乎有一個視圖有1個模型和1個集合(基於你的刪除和添加this.model),所以你有一個視圖,顯示一個單一的模型...我假設:D

然後你可以這樣做。

updatePlan : function() 
    { 
     //unique ID of the model 
     var id = $('input[ name=id ]').val(); 
     this.model.set({id: id}); 
     this.model.save(); 
    } 

我覺得那麼問題可能只是您最初的「邏輯」,你不編輯集合中的典範。 您編輯一個模型,該模型恰好屬於一個集合。 那麼事件將觸發兩個模型和model.collection,就比如你設定的ID,更改:ID事件將觸發並觸發任何約束力要麼你的模型其收藏

希望它能幫助:)