Ember-data:如何在控制器操作之间共享和更新事务中的对象?

pla*_*nhh 6 transactions nested-attributes ember.js ember-data

我在GitHub上找到了https://github.com/dgeb/ember_data_example下的ember-data的一个很好的工作示例,并尝试通过嵌套资源('has_many:comments')扩展它.在原始示例中,每次打开编辑视图时都会创建一个新事务,如果编辑模式处于离开状态,则会提交/回滚该事务.

我想在content.comments中添加一条新评论我无法做到并且因为"内容"已经在事务中而出现错误(错误:断言失败:一旦记录发生变化,您就无法将其移动到另一个事务中).

这个想法我试图意识到错了,我必须采取另一种方式吗?

App.EditContactController = Em.Controller.extend({
  content: null,

  addComment: function () {
    // ERROR here:
    this.get('content.comments').addObject(App.Comment.createRecord({body: ''}));
  },

  enterEditing: function() {
    this.transaction = this.get('store').transaction();
    if (this.get('content.id')) {
      this.transaction.add(this.get('content'));
    } else {
      this.set('content', this.transaction.createRecord(App.Contact, {}));
    }
  },

  exitEditing: function() {
    if (this.transaction) {
      this.transaction.rollback();
      this.transaction = null;
    }
  },

  updateRecord: function() {
    // commit and then clear the transaction (so exitEditing doesn't attempt a rollback)
    this.transaction.commit();
    this.transaction = null;
  }
});
Run Code Online (Sandbox Code Playgroud)

sly*_*7_7 1

我认为你可以从我所做的事情中获得灵感:https://github.com/sly7-7/ember_data_example/commit/57ee7ea6ca44e3a2fbba96fff4ad088a8d786a3c

也许简单地做this.get('content.comments').createRecord({body: ''})就会起作用。此调用引用 ManyArray.createRecord(),并使用关系所有者的事务来创建新记录。请参阅https://github.com/sly7-7/data/blob/master/packages/ember-data/lib/system/record_arrays/many_array.js#L163