Class Ember.ComputedProperty

A computed property transforms an objects function into a property.

By default the function backing the computed property will only be called once and the result will be cached. You can specify various properties that your computed property is dependent on. This will force the cached result to be recomputed if the dependencies are modified.

In the following example we declare a computed property (by calling .property() on the fullName function) and setup the properties dependencies (depending on firstName and lastName). The fullName function will be called once (regardless of how many times it is accessed) as long as it's dependencies have not been changed. Once firstName or lastName are updated any future calls (or anything bound) to fullName will incorporate the new values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Person = Ember.Object.extend({
  // these will be supplied by `create`
  firstName: null,
  lastName: null,

  fullName: function() {
    var firstName = this.get('firstName');
    var lastName = this.get('lastName');

   return firstName + ' ' + lastName;
  }.property('firstName', 'lastName')
});

var tom = Person.create({
  firstName: "Tom",
  lastName: "Dale"
});

tom.get('fullName') // "Tom Dale"

You can also define what Ember should do when setting a computed property. If you try to set a computed property, it will be invoked with the key and value you want to set it to. You can also accept the previous value as the third parameter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 Person = Ember.Object.extend({
  // these will be supplied by `create`
  firstName: null,
  lastName: null,

  fullName: function(key, value, oldValue) {
    // getter
    if (arguments.length === 1) {
      var firstName = this.get('firstName');
      var lastName = this.get('lastName');

      return firstName + ' ' + lastName;

    // setter
    } else {
      var name = value.split(" ");

      this.set('firstName', name[0]);
      this.set('lastName', name[1]);

      return value;
    }
  }.property('firstName', 'lastName')
});

var person = Person.create();
person.set('fullName', "Peter Wagenet");
person.get('firstName') // Peter
person.get('lastName') // Wagenet

Show:

Methods

Properties

No documented items

Events

No documented items