2.4 The Object Model -- Computed Properties and Aggregate Data with @each(計算的屬性和使用@each聚合數據)

1. 一般,你可能有一個計算的屬性依賴於數組中的全部元素來肯定它的值。例如,你可能想要計算controller中全部todo items的數量,以此來肯定完成了多少任務。數組

export default Ember.Controller.extend({
    todos: [
        Ember.Object.create({ isDone: true }),
        Ember.Object.create({ idDone: false }),
        Ember.Object.create({ isDone: true })    
    ],

     remaining: Ember.computed('todos.@each.isDone', function () {
         var todos = this.get('todos');
         return todos.filterBy('isDone', false).get('length');//1
     });
});    
  • 注意這裏依賴的key(todos.@each.isDone)包含特殊的key @each
  • 當如下四個事件發生時,這指示ember.js更新此計算屬性的綁定和觸發觀察者
    • todos數組中的任何對象的isDone屬性發生改變。
    • todos數組中添加一項。
    • todos中刪除一項。
    • controllertodos屬性被改變爲另一個數組。
  • 在上面的例子中,reamaining的count值是1:
import TodosController from 'app/controllers/todos';
todosController = TodosController.create();
todosController.get('remainging');

2. 若是我改變todo's isDone屬性, remaining屬性將會被自動更新:app

var todos = todosController.get('todos');
var todo = todos.objectAt(1);
todo.set('isDone', true);

todosController.get('remaining'); //0

todo = Ember.Object.Create({ isDone: false });
todos.pushObject(todo);

todosController.get('remaining');//1

3. 請注意@each不能嵌套。this

正確:todos@each.owner.namespa

錯誤:todos@each.owner.@each.namecode

相關文章
相關標籤/搜索