Computed Properties and Aggregate Data



The computed property accesses all items in an array to determine its value. It easily adds the items and removes the items from the array. The dependent key contains a special key @each which updates the bindings and observer for the current computed property.

Example

The following example shows the use of computed property and the aggregate data by using Ember's @each key −

import Ember from 'ember';

export default function() {
   var Person = Ember.Object.extend ({
      
      //todos is an array which holds the boolean values
      todos: [
         Ember.Object.create ({
            isDone: true
         }),
         Ember.Object.create ({
            isDone: false
         }),
         Ember.Object.create ({
            isDone: true
         })
      ],
      
      //dispaly the remaining values of todos
      remaining: Ember.computed('todos.@each.isDone', function() {
         var todos = this.get('todos');
         
         //return the todos array
         return todos.filterBy('isDone', false).get('length');
      }),
   });
   
   var car_obj = Person.create();
   document.write("The remaining number of cars in todo list: " + car_obj.get('remaining'));
}

Now open the app.js file and add the following line at the top of the file −

import computedaggregate from './computedaggregate';

Where, computedaggregate is a name of the file specified as "computedaggregate.js" and created under the "app" folder. Now, call the inherited "computedaggregate" at the bottom, before the export. It executes the computedaggregate function which is created in the computedaggregate.js file −

computedaggregate();

Output

Run the ember server and you will receive the following output −

Ember.js Computed Properties and Aggregate Data
emberjs_object_model.htm
Advertisements