Ember.js中的forEach移除对象未能完全移除所有对象

8

我正在尝试在Ember中迭代数组并使用removeObject()从数组中删除对象。下面的示例只会删除一些对象。我期望它能够迭代所有对象并将它们全部删除:

App = Ember.Application.create();

App.ITEM_FIXUTRES = [
  'Item 1',
  'Item 2'
];

App.ITEM_FIXTURES = App.ITEM_FIXUTRES.map(function (item) {
  return Ember.Object.create({title: item});
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return App.ITEM_FIXTURES;
  },

  actions: {
    add: function(title) {
      var items = this.modelFor('index');
      items.addObject(Ember.Object.create({title: title}));

      this.controller.set('title', '');
    },
    removeAll: function() {
      var items = this.modelFor('index');

      items.forEach(function (item) {
        // I actually only want to remove certain objects with specific
        // properties but this illustrates the issue.
        items.removeObject(item);
      });
    }
  }
});

该模板非常简单:
<script type="text/x-handlebars" id="index">
  <h4>Collection List</h4>

  <button {{action 'removeAll'}}>Remove All</button>

  <ul>
    {{#each}}
      <li>{{title}}</li>
    {{/each}}

    <li>{{input type='text' value=title action='add'}}</li>
  </ul>
</script>

Here is a JSBin: http://jsbin.com/kelinime/4/edit


1
如果我要猜的话,removeObject正在迭代时改变项目。每次迭代都会更改对象,但仍然尝试迭代原始对象。也许可以反转条件并构建一个新列表 - 而不是使用“if(cond)remove;”,可以使用“if(!cond)newList.push(item); items = newList; //或类似的东西”。 - Snnappie
1个回答

13

Snappie的说法是正确的,你不应该在迭代集合时修改它。你应该创建一个集合的副本,然后对副本进行迭代。

removeAll: function() {
  var items = this.modelFor('index'),
      list = items.toArray();

  list.forEach(function (item) {
    // I actually only want to remove certain objects with specific
    // properties but this illustrates the issue.
    items.removeObject(item);
  });
}

我知道你说你不想删除所有,但你也可以使用一个对象列表调用removeObjects并让Ember处理迭代。此外,如果需要,您还可以通过使用removeAt按索引进行删除。

http://jsbin.com/kelinime/7/edit

removeAll: function() {
  var items = this.modelFor('index'),
      list = items.toArray();
  items.removeObjects(list);
}

http://jsbin.com/kelinime/8/edit

的意思是展示一个链接,该链接指向 http://jsbin.com/kelinime/8/edit 网页。

谢谢您的帮助。在迭代集合时修改或设置项目属性是否可接受? - mschoening
肯定的是,修改集合本身是不明智的。集合中的项目是自由的。 - Kingpin2k
不错的答案。filter会创建一个新的数组,所以我发现将其结果传递给removeObjects效果很好。 - Caltor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接