| Defined in: | packages/ember-metal/lib/computed.js:437 |
|---|---|
| Module: | ember |
This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with mixins or via Ember.defineProperty().
If you pass a function as an argument, it will be used as a getter. A computed property defined in this way might look like this:
let Person = Ember.Object.extend({
init() {
this._super(...arguments);
this.firstName = 'Betty';
this.lastName = 'Jones';
},
fullName: Ember.computed('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`;
})
});
let client = Person.create();
client.get('fullName'); // 'Betty Jones'
client.set('lastName', 'Fuller');
client.get('fullName'); // 'Betty Fuller' You can pass a hash with two functions, get and set, as an argument to provide both a getter and setter:
let Person = Ember.Object.extend({
init() {
this._super(...arguments);
this.firstName = 'Betty';
this.lastName = 'Jones';
},
fullName: Ember.computed('firstName', 'lastName', {
get(key) {
return `${this.get('firstName')} ${this.get('lastName')}`;
},
set(key, value) {
let [firstName, lastName] = value.split(/\s+/);
this.setProperties({ firstName, lastName });
return value;
}
})
});
let client = Person.create();
client.get('firstName'); // 'Betty'
client.set('fullName', 'Carroll Fuller');
client.get('firstName'); // 'Carroll' The set function should accept two parameters, key and value. The value returned from set will be the new value of the property.
Note: This is the preferred way to define computed properties when writing third-party libraries that depend on or use Ember, since there is no guarantee that the user will have prototype Extensions enabled.
The alternative syntax, with prototype extensions, might look like:
fullName: function() {
return this.get('firstName') + ' ' + this.get('lastName');
}.property('firstName', 'lastName')
© 2017 Yehuda Katz, Tom Dale and Ember.js contributors
Licensed under the MIT License.
https://emberjs.com/api/ember/2.15/classes/Ember.computed