当我从模型中的数组字段中添加或删除对象时,Ember不更新模板

Ember not updating template when I add or remove an object from an array field in the model

本文关键字:对象 Ember 更新 删除 模型 数组 添加 字段      更新时间:2023-09-26

我得到了一个包含数组对象字段的模型它看起来是这样的

App.Post = DS.Model.extend({
    ...
    codes: attr(),  
    ...
});
and Codes looks like this 
codes: [
{
    code: stuff
    comment: stuff_1
    other_things: other_stuff
},
{
    ...
},
{
    ...
}
...
]

现在我有了一个添加/删除按钮它有附加的动作这就是它们的作用

add_code_input: function() {
        var codes = this.get('model.codes');
        var self = this;
        var last_code = codes[codes.length-1];
        // Cannot edit as an ember.set error is occurring
        last_code.code = 'Add new (please change)';
        last_code.code_type = "";
        last_code.comment = "";
        console.log(last_code);
        codes.push(last_code);
        this.set('model.codes', codes);

        console.log(codes);
},
remove_code_input: function() {
    var codes = this.get('model.codes');
    codes.pop();
    console.log(codes);
    this.set('model.codes', codes);
}

所以删除工作正常,但添加不工作。

当我尝试更新last_code时,它给了我这个错误:Uncaught Error: Assertion Failed: You must use Ember.set() to access this property (of [object Object])

我想添加一个用户可以修改的虚拟对象。

所以第一个问题是弄清楚如何正确地将虚拟对象添加到数组中,其次如何随着模型的变化而更新模板。

您应该使用arr.pushObject(obj)arr.popObject()来操作Ember中的数组(将其视为数组的setter/getter)。

是代码实际上只是attr(),因为它看起来像一个DS记录。

如果它是一个记录,你可以使用record.set('foo', 'bar');如果它只是一个POJO,你可以使用Ember.set(obj, 'foo', 'bar')

它应该像这样简单(我假设你在这里使用和ObjectController)

var newCode = {
  code:'foo'
};
this.get('codes').pushObject(newCode);