[英]Ember-Data transaction error
我在Ember-Data交易中遇到問題。
我有一個像這樣的DS.Model
App.MyModel = DS.Model.extend({
id: DS.attr(),
answers: DS.hasMany('App.Answer') // another model
});
然后像這樣在路由中稍后啟動
model: function(){
var transaction = this.get('store').transaction();
return transaction.createRecord(App.MyModel, {
id: '1'
});
}
我有一個使用事務和提交向后端服務器發出請求的模型。
this.get('content.transaction').commit();
目的是在服務器端更新答案並將其發送給我。 如果內容尚未更新,我稱之為
this.get('content').reload();
並再次發送請求。
這一切都很好。 如果找到ID,則會填充答案。
我的問題是,有時候,根據我從服務器獲得的信息,我必須提出另一個服務器請求。 初始請求可以與
this.get('content.transaction').commit();
但是當我嘗試重新加載事務時,出現如下錯誤
Uncaught Error: Attempted to handle event `loadedData` on <App.Answer> while in state rootState.loaded.updated.uncommitted. Called with undefined
現在,當我刪除重新加載時,不再出現錯誤,而且當我在“網絡”選項卡下檢查Chrome的控制台時,我可以看到我想要的結果已發回,但在我的DS模型中沒有更新。 答案是不確定的。
有人知道為什么會這樣嗎? 我使用交易有誤嗎?
編輯
Application.SearchController = Ember.ObjectController.extend({
isComplete: function () {
return this.get('content.answers.length') !== 0;
},
search: function () {
this.get('content.transaction').commit();
var record = this.get('content');
var interval = setInterval(function (controller) {
if (controller.get('isComplete')) {
controller.transitionToRoute("search.view");
clearInterval(interval);
} else {
record.reload();
}
}, 5000, this);
}
});
因此,基本上,我在完成設置模型並將其設置為內容的過程中做了一些工作,該模型具有一個ID,該ID將在服務器端使用,並隨搜索結果一起發送回去,然后添加到“答案”中。
正常工作,直到找到多個結果。 然后創建一個新模型,並在具有不同內容的其他控制器上再次調用搜索功能。 這次是在記錄行。
我得到的錯誤未被捕獲的錯誤:試圖處理事件loadedData
上,而在狀態rootState.loaded.updated.uncommitted。 用未定義調用
因此,服務器仍然以正確的結果進行響應,但是客戶端不會更新“答案”。
您的MyModel
記錄是本地修改的(客戶端)。 調用reload
會嘗試更新它,這在記錄的當前狀態中是禁止的。
您可以使用以下命令進行檢查:
console.log( this.get('content.stateManager.currentState.path') );
this.get('content').reload();
這將在您的控制台中顯示該記錄處於uncommitted
狀態。
更新:
您不能使用計時器。 一切都是異步的,您不能保證在此間隔內將更新模型。 這意味着在提交記錄時,您可以同時重新加載它(這會產生您看到的錯誤)。
您想要的是這樣的:
Application.SearchController = Ember.ObjectController.extend({
search: function () {
var record = this.get('content'),
controller = this;
record.one('didCommit', function() {
controller.transitionToRoute("search.view");
});
record.transaction.commit();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.