我在Ember.js中创建了一个简单的控制器,purpuse是将Person添加到商店,使用REST Adapter将其保存到服务器并获取ID并使用ID更新行。
我的代码如下所示:
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()并使用Abraham创建新记录。接下来,我允许用户编辑名称。在他推送保存后,我以这种方式从模板调用保存功能:
{{action save on="submit"}}
新记录作为一行正确保存到数据库。用户被重定向到人员列表。但突然之间,似乎在人员名单上亚伯拉罕是重复的。
我调查了商店,有两行具有相同的数据和相同的ID。 Userid与众不同。在数据库中只有一行。
那么在这种情况下如何防止Ember.js重复添加行呢?
答案 0 :(得分:3)
由于您正在寻找详细的规范答案,我将假设您想要做“Ember Way”的事情。
我们假设这是您的Person
模型:
App.Person = DS.Model.extend({
firstName : DS.attr('string'),
lastName : DS.attr('string')
});
通常,您需要使用model
的{{1}}挂钩来设置控制器的内容。
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:http://jsbin.com/ucanam/1201/edit
答案 1 :(得分:1)
因为记录永远不在商店里。实际上你应该犯这样的错误。
创建新记录的正确方法是
currentRecord = this.store.createRecord('person');
然后保存该记录:
currentRecord.save();