我还没有找到以下任何内容,您可能会对此有任何帖子或指南,我们将不胜感激!
我正在尝试使用表单和路由器创建新记录。我这样做的方法是在路由器中设置模型,然后在用户通过操作提交表单时保存记录。
我已经看过其他一些例子,作者做了一个" createRecord"在控制器中,使用" get"从表单中获取值。或" getProperties"。但是,在我的下面的代码中,它似乎更简单:
Dashboard.CreateAccountRoute = Ember.Route.extend({
model: function() {
return this.store.createRecord('account', {});
},
actions: {
createAccount: function () {
var account = this.modelFor('create_account');
var self = this;
account.save().then(function(account){
self.flashMessage('The account was added successfully!', 'alert-success');
self.transitionTo("accounts");
}, function(reason) {
self.flashMessage('There was an error saving the account. Please try again.', 'alert-error');
console.log(reason);
});
}
}
});
当然,问题在于,如果用户没有提交表单,该记录仍会添加到本地存储中。否则,它将从表单中的记录中按预期的设置值工作。
如果在行动结束之前我怎样才能完成上述任务而不保存任何东西" createAccount"?
答案 0 :(得分:2)
您可以使用路由的deactivate
挂钩来回滚模型。这是一个例子:
deactivate: function() {
var model = this.get('controller.model');
if (model != null) {
model.rollback();
}
}
答案 1 :(得分:1)
您可以使用willTransition
事件。以下是我们的应用程序中的一个真实示例:
App.FlavorNewRoute = Ember.Route.extend({
setupController: function(controller) {
var game = this.modelFor('game');
var newFlavor = this.store.createRecord('flavor', {
name: '',
blueprintName: game.get('blueprintName'),
organizationId: game.get('organizationId'),
isArchived: false,
isLocked: false,
entries: []
});
controller.set('content', newFlavor);
},
actions: {
willTransition: function(transition) {
var flavor = this.controller.get('content');
if(flavor.get('isNew') && flavor.get('isDirty')) {
flavor.destroyRecord();
}
}
}
});