2

我有一个保存多个任务列表的应用程序。每个任务列表都有多个任务。每个任务都有多个评论。

更新到新的 Ember 数据后,我不得不废弃我的记录创建代码。目前我有这个,它不起作用。虽然它没有抛出任何错误,但我的模型似乎没有更新。

App.TaskController = Ember.ArrayController.extend({
  needs : ['list'],
  isEditing : false,
  actions : {
    addTask : function(){
      var foo = this.store.createRecord('task', { 
        description : '',
        list : this.get('content.id'),
        comments : []  
      });
      foo.save();
      console.log('Task Created!');
    },
    edit : function(){
        this.set('isEditing', true);
    },
    doneEditing : function(){
        this.set('isEditing', false);
    }
  }
});

有谁知道在这种情况下如何创建新任务(以及如何创建新评论)?

在这里看小提琴:http: //jsfiddle.net/edchao/W6QWj/

4

2 回答 2

2

是的,您需要列表控制器中的 pushObject。

我会这样做 addTask 像这样,现在几乎每个 ember 数据中的方法都返回一个承诺

App.TaskController = Ember.ArrayController.extend({
  needs : ['list'],
  listController:Ember.computed.alias('controllers.list'),
  isEditing : false,
  actions : {
    addTask : function(){
        var listId = this.get('listController.model.id'),
        list = this,
        store = this.get('store');
        console.log('listId',listId);
        store.find('task').then(function(tasks){
            var newId = tasks.get('lastObject.id') + 1,
            newTask = store.createRecord('task', { 
                id:newId,
                description : '',
                list : listId,
                comments : []  
           });
            newTask.save().then(function(newTaskSaved){
                list.pushObject(newTaskSaved);
                console.log('Task Created!');
            });
        });
    },
    edit : function(){
       this.set('isEditing', true);
    },
    doneEditing : function(){
        this.set('isEditing', false);
    }
  }
});

我认为正确查找 id 非常重要,在这里我使用 find 进行固定,但其余适配器将是分配 id 并将其设置在响应中的后端

JSFiddle http://jsfiddle.net/W6QWj/2/

于 2013-10-22T08:36:01.873 回答
1

好的,所以我已经回答了我自己的问题。我错过了 pushObject() 方法。这是另一种做事方式。虽然我不确定这是否是最佳实践,因为它确实会引发错误“断言失败:您只能将'列表'记录添加到此关系”

App.ListController = Ember.ObjectController.extend({
  actions:{
    addTask : function(){
      var foo = this.store.createRecord('task', { 
        description : '',
        list : this.get('content.id'),
        comments : []  
      });
      this.get('tasks').pushObject(foo);
      foo.save();
    }
  }
});
于 2013-10-22T15:42:26.417 回答