gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:07:07 24 4
gpt4 key购买 nike

我正在尝试遍历 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

关于javascript - forEach 中的 Ember.js removeObject 不删除所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23478409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com