Ember.js中的removeObject在forEach中不删除所有对象
Ember.js removeObject in forEach not removing all Objects
我试图迭代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 相关文章:
- 解析JSON并从中删除对象会出错
- 在特定条件下从存储在localStorage中的阵列中删除对象
- Es6:能够在设置/更新/删除对象属性时调用自定义方法
- 正在从列表中删除对象
- 删除对象时终止setInterval
- 在JavaScript中高效地删除对象
- 使用javascript(ajax,jquery?)从表中删除对象(用户等)
- 从范围中删除对象时,它会在 Angularjs 中隐藏其余对象
- 如何正确地从数组中删除对象
- 捕捉.svg — 单击其中一个元素时删除对象
- 如何删除对象数组中的对象:jquery
- 下划线.js,根据键值删除对象数组中的重复项
- 如何在Immutable中从数组中删除对象
- 删除对象属性在执行删除操作之前生效
- 使用indexOf从列表中删除对象
- 从数组中删除对象
- 如何使用.bind(this)删除对象的事件侦听器
- 正在创建事件侦听器以从本地存储中删除对象
- 如何通过引用(javascript)从数组中删除对象
- 如何按条件删除对象中的对象