你应该回滚模型:
this.get('model').rollback();
但是,依靠用户单击“取消”可能会出现问题 - 如果他们使用后退按钮导航会怎样?根据我的经验,最好将表单绑定到模型对象的副本,这样您就可以轻松地丢弃更改。 “保存”操作将从临时对象复制回路线模型并保存。另外,请考虑服务器未能保存的影响。您可能应该在致电save() 时使用then(),这样您就可以警告用户/恢复/回滚等。
您可以将每个属性复制到“缓冲区”属性并在表单模板中执行以下操作:
{{#with buffer}}
{{input value=fieldOne}}
{{input value=fieldTwo}}
{{/with}}
要在模型对象上创建 attributes 计算属性,请添加:
attributes: function() {
var model = this,
result = [];
Ember.keys(this.get('data')).forEach(function(key) {
result.push(Ember.Object.create({
model: model,
key: key,
valueBinding: 'model.' + key
}));
});
return result;
}.property()
然后,要创建一个临时缓冲区供您的表单使用,您可以在控制器上执行此操作:
setupController: function(controller, model) {
var buffer={};
controller.set('model', model);
model.get('attributes').forEach(function(item) {
buffer[item.get('key')]= item.get('value');
});
controller.set('buffer', buffer);
this._super(controller, model);
}
我个人将它们用作Mixins,因此我可以轻松地将它们添加到我的所有模型对象并编辑控制器。