Class Ember.ComputedProperty
publicA computed property transforms an object's 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 depends 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 property
dependencies (depending on firstName and lastName). The fullName function
will be called once (regardless of how many times it is accessed) as long
as its dependencies have not changed. Once firstName or lastName are updated
any future calls (or anything bound) to fullName will incorporate the new
values.
var 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.
var 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'