Ember-Data事务错误

时间:2013-04-29 22:45:11

标签: ember.js ember-data

我遇到了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,然后将搜索结果发送回“回答”。

这项工作正常,直到找到多个结果。然后创建一个新模型,并在具有不同内容的不同控制器上再次调用搜索功能。这一次就行了     record.reload();

我收到错误     未捕获错误:在状态rootState.loaded.updated.uncommitted中尝试处理事件loadedData。用未定义的

调用

因此服务器仍然会以正确的结果作出响应,但客户端的“答案”不会更新。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

第一次提交后,交易将被置于默认交易中。

Error Attempted to handle event `loadedData` : Object not updated after deleteRecord

请记住始终先设置路由器。