如何修改由Ember控制器管理的阵列中的元素?

J S*_*gue 5 ember.js

我可能错过了一些非常愚蠢的东西,(Ember newbie)但是我无法弄清楚如何修改一个在我的Ember控制器管理下的数组,除了设置一个全新的数组.

例如.我的控制器中有以下测试功能.当用户单击时,我想要使用新值修改受控阵列的每个元素(或者它可以是单个元素).

我明白你应该通过"设置"来让Ember知道这些变化,所以我认为这样可行:

clickHandler:function(e){
    var temp = this.get("itemList").copy(); // copy it
    for (var i = 0; i < temp.length; i++) { 
        temp[i].desc = "CANCELLED";     // change it
    }
    this.set('itemList', temp); // put it back
}
Run Code Online (Sandbox Code Playgroud)

我制作数组的副本,修改它,然后重新设置它.但不知怎的,Ember抱怨第4行,我在那里修改了temp [i] .desc的内容,说我必须使用Ember.Set.我假设我可以修改"离线"副本,然后将其设置回来,但是不行,我无法弄清楚原因.其他数组操作,如shift/unshift/pop似乎可以工作.

mav*_*ein 12

你的方法看起来不是很诡异.这段代码可行:

clickHandler:function(e){
    var itemList = this.get("itemList");
    itemList.forEach(function(item){ // for iterating over an array, always use the forEach function
        item.set("desc", "CANCELLED"); // you have to call this set()-function to make changes to an Ember Object
    });
}
Run Code Online (Sandbox Code Playgroud)

为什么需要调用set()方法而不能使用直接访问方法?

set() - 方法使Ember能够执行其自动绑定魔术.调用此方法时,它会调度需要对依赖于已修改属性的对象执行的所有内容.最简单的示例是显示需要更新的给定属性的模板.

这里对上面代码的一个可能的改进使得更加晦涩: 你可以使用ArrayController来管理你的itemList.在这种情况下,您可以将itemList设置为控制器的content属性.您会注意到,如果处理数组,许多教程都会利用此控制器.

App.ItemListController = Ember.ArrayController.extend({
    content : null, //set your itemList into this property
    clickHandler:function(e){
        this.get("content").setEach("desc", "CANCELLED");
    }
});
Run Code Online (Sandbox Code Playgroud)