我正在尝试迭代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
答案 0 :(得分: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);
});
}
http://jsbin.com/kelinime/7/edit
我意识到你说你并没有尝试删除所有内容,但你也可以用一个对象列表调用removeObjects
,然后让Ember处理迭代。此外,如果案例出现,您也可以使用removeAt
removeAll: function() {
var items = this.modelFor('index'),
list = items.toArray();
items.removeObjects(list);
}