Ember.computed

public

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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:

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
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:

1
2
3
fullName: function() {
  return this.get('firstName') + ' ' + this.get('lastName');
}.property('firstName', 'lastName')