gpt4 book ai didi

ember.js - Ember.js 如何防止 CreateRecord 和 Commit 重复记录?

转载 作者:行者123 更新时间:2023-12-02 05:45:04 25 4
gpt4 key购买 nike

我在 Ember.js 中创建了一个简单的 Controller ,目的是将一个人添加到商店,使用 REST 适配器将其保存到服务器并获取 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。用户标识不同。在数据库中只有一行。

那么在这种情况下如何防止 Ember.js 复制添加的行?

最佳答案

由于您正在寻找详细的规范答案,我将假设您想要以“Ember 方式”做事。

假设这是您的 Person 模型:

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

通常,您需要使用 Routemodel 钩子(Hook)来设置 Controller 的内容。

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

关于ember.js - Ember.js 如何防止 CreateRecord 和 Commit 重复记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18058830/

25 4 0
文章推荐: ember.js - 没有 Ember 数据的 Ajax - 未捕获的类型错误 : Object # has no method 'forEach'
文章推荐: php - 比较变量 PHP