Javascript forEach中的Ember.js removeObject未删除所有对象
我试图在Ember中迭代数组,并使用Javascript forEach中的Ember.js removeObject未删除所有对象,javascript,ember.js,Javascript,Ember.js,我试图在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(
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>
收藏清单
全部删除
{{{#各}
- {{title}}
{{/每个}}
- {{input type='text'value=title action='add'}
这里有一个JSBin:上面的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
按索引删除
removeAll: function() {
var items = this.modelFor('index'),
list = items.toArray();
items.removeObjects(list);
}
如果让我猜一猜的话,removeObject在迭代过程中会对项目进行变异。每次迭代都会更改对象,但它仍在尝试遍历原始对象。相反,可能会否定该条件并构建一个新列表-而不是
if(cond)remove代码>使用if(!cond)newList.push(项目);items=newList;//或者类似的
谢谢您的帮助。在我正在迭代的集合中修改或设置项的属性可以接受吗?当然,修改集合本身是不明智的。集合中的项目是免费的filter
创建一个新数组,因此我发现将该数组的结果传递给removeObjects
效果很好。