msc*_*ing 8 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({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);
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
模板非常简单:
<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>
Run Code Online (Sandbox Code Playgroud)
这是一个JSBin:http://jsbin.com/kelinime/4/edit
Kin*_*n2k 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);
});
}
Run Code Online (Sandbox Code Playgroud)
http://jsbin.com/kelinime/7/edit
我意识到你说你不是要删除所有,但你也可以调用removeObjects一个对象列表,让Ember处理迭代.此外,如果案例出现,您也可以使用索引删除索引removeAt.
removeAll: function() {
var items = this.modelFor('index'),
list = items.toArray();
items.removeObjects(list);
}
Run Code Online (Sandbox Code Playgroud)
http://jsbin.com/kelinime/8/edit
| 归档时间: |
|
| 查看次数: |
6171 次 |
| 最近记录: |