英文原址:http://emberjs.com/guides/object-model/computed-properties-and-aggregate-data/
通常,你可能会定义一个计算型属性,它的值依赖于一个数组中的所有元素的值。比如说,你可能想要对controller中的所有todo项目来计数,以统计它们中的多少是完成了的,下面说明了它可能会是什么样的:
App.TodosController = Ember.Controller.extend({
todos: [
Ember.Object.create({ isDone: false })
],
remaining: function() {
var todos = this.get('todos');
return todos.filterBy('isDone', false).get('length');
}.property('todos.@each.isDone')
});
注意这里,它依赖的关键字是todos.@each.isDone,其中含有关键字@each。这指示Ember在下列事件发生时,自动为这个计算型属性更新绑定并且触发观察事件:
- 任意一个todos数组中的元素的isDone属性改变时
- 一个新的元素被添加到todos数组
- 从todos数组中删除一个元素
- controller中的todos数组本身被改变以指向不同的数组
在上面的例子中,remaining的值是1
App.todosController = App.TodosController.create();
App.todosController.get('remaining');
// 1
如果我们改变todo的isDone属性,remaining属性的值会自动更新:
var todos = App.todosController.get('todos');
var todo = todos.objectAt(0);
todo.set('isDone', true);
App.todosController.get('remaining');
// 0
todo = Ember.Object.create({ isDone: false });
todos.pushObject(todo);
App.todosController.get('remaining');
// 1
请注意,@each只能对往下一层生效。你不能对它使用嵌套的形式,比如todos.@each.owner.name或者todos.@each.owner.@each.name。