Ember.js中的removeObject在forEach中不删除所有对象

Ember.js removeObject in forEach not removing all Objects

本文关键字:删除 对象 forEach js 中的 removeObject Ember      更新时间:2023-09-26

我试图迭代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>

这是一个JSBin: http://jsbin.com/kelinime/4/edit

上面的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);
  });
}
http://jsbin.com/kelinime/7/edit

我知道你说你不想删除所有的对象,但是你也可以用对象列表调用removeObjects,让Ember处理迭代。此外,如果出现这种情况,您也可以通过索引删除,通过使用removeAt

removeAll: function() {
  var items = this.modelFor('index'),
      list = items.toArray();
  items.removeObjects(list);
}
http://jsbin.com/kelinime/8/edit