Function

computed (dependentKeys*, func) ComputedProperty public

Module: @ember/object
import { computed } from '@ember/object';
dependentKeys*
String
Optional dependent keys that trigger this computed property.
func
Function
The computed property function.
returns
ComputedProperty
property descriptor instance

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

import EmberObject, { computed } from '@ember/object';

let Person = EmberObject.extend({
  init() {
    this._super(...arguments);

    this.firstName = 'Betty';
    this.lastName = 'Jones';
  },

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

import EmberObject, { computed } from '@ember/object';

let Person = EmberObject.extend({
  init() {
    this._super(...arguments);

    this.firstName = 'Betty';
    this.lastName = 'Jones';
  },

  fullName: 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')

© 2020 Yehuda Katz, Tom Dale and Ember.js contributors
Licensed under the MIT License.
https://api.emberjs.com/ember/2.18/functions/@ember%2Fobject/computed