Dee*_*tha 18 ember.js ember-data
我的模型定义为:
App.Answer = DS.Model.extend({
name: DS.attr('string'),
layoutName: DS.attr('string')
});
App.Question = DS.Model.extend({
name: DS.attr('string'),
answers: DS.hasMany('answer', {async: true})
});
Run Code Online (Sandbox Code Playgroud)
我有一个组件,允许删除和添加问题模型的答案.该组件带有"应用"和"取消"按钮,当用户单击"取消"时,我希望还原所有更改(添加/删除答案).目前回滚不起作用,我在使用rest适配器时尝试了model.reload(),但这对我来说也不起作用.知道如何在这种情况下进行回滚吗?
当使用其余的适配器时,我几乎陷入了这里指出的问题:使用HasMany的EmberJS取消(回滚)对象
谢谢,迪
更新:
由于我无法以预期的方式执行回滚,因此我执行了以下步骤:
1) get all the answers back from the server
2) remove answer association from the question
3) manually add answer association to the question model from data received from server
Run Code Online (Sandbox Code Playgroud)
这似乎运作良好但令人遗憾的是我得到了一个我无法摆脱的错误.
这是更新进展的jsbin:http://jsbin.com/uWUmUgE/2/
在这里,您可以创建新的答案,然后将其附加到问题并进行回滚.但是,如果您按照这些步骤操作,您将看到我面临的问题:
1) delete an answer
2) add an answer
3) perform rollback
4) add an answer
Run Code Online (Sandbox Code Playgroud)
它会抛出此错误:
错误:didSetProperty在状态root.deleted.uncommitted中尝试处理事件.用{name:position,oldValue:1,originalValue:1,value:2}调用.
我将非常感谢您提供的任何帮助.
解决方法:
一个简单的解决方法是隐藏删除的答案.我修改了模型有点像:
App.Answer = DS.Model.extend({
name: DS.attr('string'),
layoutName: DS.attr('string'),
markToDelete: DS.attr('boolean', {default: false})
});
Run Code Online (Sandbox Code Playgroud)
我的回滚功能有这样的逻辑:
answers.forEach(function (answer) {
if(!answer.get('id')){
//newly created answer models that has not persisted in DB
question.get('answers').removeObject(answer);
answer.deleteRecord();
} else {
answer.rollback();
}
});
Run Code Online (Sandbox Code Playgroud)
我不确定你的范围,但对于这种关系(我实际上正在回滚属于这里,但我很好奇这是否有任何帮助)
App.Appointment = DS.Model.extend({
name: DS.attr('string'),
customer: DS.belongsTo('customer', {async: true})
});
App.Customer = DS.Model.extend({
name: DS.attr('string'),
appointments: DS.hasMany('appointment', {async: true})
});
Run Code Online (Sandbox Code Playgroud)
我可以回滚约会,并且它的 hasMany 客户模型像这样(从我的路线内)
App.AppointmentRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
var context = this.get('context');
var dirty =context.get('isDirty');
var dirtyCustomer=context.get('customer.isDirty');
var message = "foo";
if ((dirty || dirtyCustomer) && confirm(message)) {
transition.abort();
}else{
context.get('customer').get('content').rollback();
context.rollback();return true;
}
}
});
Run Code Online (Sandbox Code Playgroud)