2014-01-10 29 views
18

我定義爲車型:執行回滾用的hasMany關係

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}) 
}); 

我有一個組件,它允許刪除和添加回答以下問題的模式。該組件帶有應用和取消按鈕,當用戶點擊取消時,我希望恢復所有的更改(增加/刪除答案)。目前回滾沒有辦法,我使用休息適配器時,事件嘗試了model.reload(),這對我也不起作用。任何想法如何在這種情況下做回滾?

當使用其他適配器,我幾乎摔倒在問題指向:EmberJS cancel (rollback) object with HasMany

感謝,迪伊

UPDATE:

因爲我無法執行回滾預期的方式,我執行了這些步驟:

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 

這似乎很好,但很遺憾我遇到了這個我無法擺脫的錯誤。

下面是更新進度jsbin:http://jsbin.com/uWUmUgE/2/

在這裏,你可以創建新的答案,然後將其追加質疑和不回滾了。但是,如果你遵循這些步驟,你會看到這個問題,我面對:

1) delete an answer 
2) add an answer 
3) perform rollback 
4) add an answer 

它拋出這個錯誤: 錯誤:試圖在同時處理事件didSetProperty狀態root.deleted.uncommitted。用{名稱:位置,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}) 
}); 

我的回滾功能有這樣的邏輯:

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(); 
    } 
}); 

回答

2

我不知道你的範圍,但這種關係(實際上,我回滾屬於關聯這裏,但我很好奇,如果這有助於以任何方式)

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}) 
    }); 

我能夠回滾同時任命和它的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; 
    } 
} 
}); 
+0

嗨@Toran感謝您的迴應。當我嘗試從處理回滾的組件操作中獲取上下文時,它會返回組件實例本身。在你的情況下,你會得到什麼? –

+0

啊,對不起,我的例子是從一個路線內(我還沒有做任何事情W /一個組件,所以我不知道這將是相似/否) –