2013-08-05 61 views
3

我在Ember.js中創建了一個簡單的控制器,它的作用是將一個Person添加到存儲中,並將其與REST適配器一起保存到服務器並獲取該ID並使用該ID更新該行。如何防止在Ember.js中複製記錄的CreateRecord和Commit?

我的代碼如下所示:

App.AddPersonController = Ember.ObjectController.extend({ 
    newRecord: function() { 
     currentRecord = App.Person.createRecord({name: "Abraham"}); 
     this.set('content', currentRecord); 
    } 
    save : function() { 
     var result = this.get('store').commit(); 
     this.transitionToRoute('people.list'); 
     return result; 
    } 
}); 

我打電話newRecord()和新的記錄與亞伯拉罕創建。接下來,我允許用戶編輯名稱。在他按下保存之後,我通過模板調用保存功能:

{{action save on="submit"}} 

將新記錄正確保存到數據庫中作爲一行。用戶被重定向到人員列表。但突然間,人們的名單上亞伯拉罕似乎重複了。

我調查了商店,並有兩行具有相同的數據和相同的ID。 Userid是不同的。在數據庫中只有一行。

那麼如何防止在這種情況下通過Ember.js重複添加行?

回答

1

因爲記錄從不在商店中。你應該在這樣做時發生錯誤。

正確的方法來建立一個新的記錄是

currentRecord = this.store.createRecord('person'); 

然後保存該記錄的:

currentRecord.save(); 
3

既然你正在尋找一個詳細的規範答案,我要承擔你想做的事情是「灰燼之路」。

讓我們假設這是你的Person型號:

App.Person = DS.Model.extend({ 
    firstName : DS.attr('string'), 
    lastName : DS.attr('string') 
}); 

一般來說,你會希望使用model鉤子上Route來爲您的控制器的內容。

App.AddPersonRoute = Ember.Route.extend({ 
    model : function(){ 
    return this.store.createRecord('person',{ 
     firstName : 'fake', 
     lastName : 'name' 
    }); 
    } 
}); 

然後在你Controller你可以檢索content對象,調用save,然後再過渡到你想去的地方。

App.AddPersonController = Ember.ObjectController.extend({ 
    actions : { 
    save : function(){ 
     this.get('model').save(); 
     this.transitionToRoute('index'); 
    } 
    } 
}); 

這裏有一個JSBin使用FixtureController顯示這個行動:http://jsbin.com/ucanam/1201/edit