Class @ember/object/computed

Module: @ember/object

alias (dependentKey) ComputedProperty public

Module: @ember/object
import { alias } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which creates an alias to the original value for property.

Creates a new property that is an alias for another property on an object. Calls to get or set this property behave as though they were called on the original property.

Example:

import { set } from '@ember/object';
import { alias } from '@ember/object/computed';

class Person {
  name = 'Alex Matchneer';

  @alias('name') nomen;
}

let alex = new Person();

alex.nomen; // 'Alex Matchneer'
alex.name;  // 'Alex Matchneer'

set(alex, 'nomen', '@machty');
alex.name;  // '@machty'

Classic Class Example:

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

let Person = EmberObject.extend({
  name: 'Alex Matchneer',

  nomen: alias('name')
});

let alex = Person.create();

alex.nomen; // 'Alex Matchneer'
alex.name;  // 'Alex Matchneer'

set(alex, 'nomen', '@machty');
alex.name;  // '@machty'

and (dependentKey) ComputedProperty public

Module: @ember/object
import { and } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which performs a logical `and` on the values of all the original values for properties.

A computed property that performs a logical and on the original values for the provided dependent properties.

You may pass in more than two properties and even use property brace expansion. The computed property will return the first falsy value or last truthy value just like JavaScript's && operator.

Example:

import { set } from '@ember/object';
import { and } from '@ember/object/computed';

class Hamster {
  @and('hasTent', 'hasBackpack') readyForCamp;
  @and('hasWalkingStick', 'hasBackpack') readyForHike;
}

let tomster = new Hamster();

tomster.readyForCamp; // false

set(tomster, 'hasTent', true);
tomster.readyForCamp; // false

set(tomster, 'hasBackpack', true);
tomster.readyForCamp; // true

set(tomster, 'hasBackpack', 'Yes');
tomster.readyForCamp; // 'Yes'

set(tomster, 'hasWalkingStick', null);
tomster.readyForHike; // null

Classic Class Example:

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

let Hamster = EmberObject.extend({
  readyForCamp: and('hasTent', 'hasBackpack'),
  readyForHike: and('hasWalkingStick', 'hasBackpack')
});

let tomster = Hamster.create();

tomster.readyForCamp; // false

set(tomster, 'hasTent', true);
tomster.readyForCamp; // false

set(tomster, 'hasBackpack', true);
tomster.readyForCamp; // true

set(tomster, 'hasBackpack', 'Yes');
tomster.readyForCamp; // 'Yes'

set(tomster, 'hasWalkingStick', null);
tomster.readyForHike; // null

bool (dependentKey) ComputedProperty public

Module: @ember/object
import { bool } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which converts to boolean the original value for property

A computed property that converts the provided dependent property into a boolean value.

Example:

import { set } from '@ember/object';
import { bool } from '@ember/object/computed';


class Hamster {
  @bool('numBananas') hasBananas
}

let hamster = new Hamster();

hamster.hasBananas; // false

set(hamster, 'numBananas', 0);
hamster.hasBananas; // false

set(hamster, 'numBananas', 1);
hamster.hasBananas; // true

set(hamster, 'numBananas', null);
hamster.hasBananas; // false

Classic Class Example:

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


let Hamster = EmberObject.extend({
  hasBananas: bool('numBananas')
});

let hamster = Hamster.create();

hamster.hasBananas; // false

set(hamster, 'numBananas', 0);
hamster.hasBananas; // false

set(hamster, 'numBananas', 1);
hamster.hasBananas; // true

set(hamster, 'numBananas', null);
hamster.hasBananas; // false

collect (dependentKey) ComputedProperty public

Module: @ember/object
import { collect } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which maps values of all passed in properties to an array.

A computed property that returns the array of values for the provided dependent properties.

Example:

import { set } from '@ember/object';
import { collect } from '@ember/object/computed';

class Hamster {
  @collect('hat', 'shirt') clothes;
}

let hamster = new Hamster();

hamster.clothes; // [null, null]

set(hamster, 'hat', 'Camp Hat');
set(hamster, 'shirt', 'Camp Shirt');
hamster.clothes; // ['Camp Hat', 'Camp Shirt']

Classic Class Example:

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

let Hamster = EmberObject.extend({
  clothes: collect('hat', 'shirt')
});

let hamster = Hamster.create();

hamster.clothes; // [null, null]

set(hamster, 'hat', 'Camp Hat');
set(hamster, 'shirt', 'Camp Shirt');
hamster.clothes; // ['Camp Hat', 'Camp Shirt']

deprecatingAlias (dependentKey, options) ComputedProperty public

Module: @ember/object

Available since v1.7.0

import { deprecatingAlias } from '@ember/object/computed';
dependentKey
String
options
Object
Options for `deprecate`.
returns
ComputedProperty
computed property which creates an alias with a deprecation to the original value for property.

Creates a new property that is an alias for another property on an object. Calls to get or set this property behave as though they were called on the original property, but also print a deprecation warning.

Example:

import { set } from '@ember/object';
import { deprecatingAlias } from '@ember/object/computed';

class Hamster {
  @deprecatingAlias('cavendishCount', {
    id: 'hamster.deprecate-banana',
    until: '3.0.0'
  })
  bananaCount;
}

let hamster = new Hamster();

set(hamster, 'bananaCount', 5); // Prints a deprecation warning.
hamster.cavendishCount; // 5

Classic Class Example:

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

let Hamster = EmberObject.extend({
  bananaCount: deprecatingAlias('cavendishCount', {
    id: 'hamster.deprecate-banana',
    until: '3.0.0'
  })
});

let hamster = Hamster.create();

set(hamster, 'bananaCount', 5); // Prints a deprecation warning.
hamster.cavendishCount; // 5

empty (dependentKey) ComputedProperty public

Module: @ember/object

Available since v1.6.0

import { empty } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which returns true if the value of the dependent property is null, an empty string, empty array, or empty function and false if the underlying value is not empty.

A computed property macro that returns true if the value of the dependent property is null, an empty string, empty array, or empty function.

Example:

import { set } from '@ember/object';
import { empty } from '@ember/object/computed';

class ToDoList {
  constructor(todos) {
    set(this, 'todos', todos);
  }

  @empty('todos') isDone;
}

let todoList = new ToDoList(
  ['Unit Test', 'Documentation', 'Release']
);

todoList.isDone; // false
set(todoList, 'todos', []);
todoList.isDone; // true

Classic Class Example:

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

let ToDoList = EmberObject.extend({
  isDone: empty('todos')
});

let todoList = ToDoList.create({
  todos: ['Unit Test', 'Documentation', 'Release']
});

todoList.isDone; // false
set(todoList, 'todos', []);
todoList.isDone; // true

equal (dependentKey, value) ComputedProperty public

Module: @ember/object
import { equal } from '@ember/object/computed';
dependentKey
String
value
String|Number|Object
returns
ComputedProperty
computed property which returns true if the original value for property is equal to the given value.

A computed property that returns true if the provided dependent property is equal to the given value.

Example:

import { set } from '@ember/object';
import { equal } from '@ember/object/computed';

class Hamster {
  @equal('percentCarrotsEaten', 100) satisfied;
}

let hamster = new Hamster();

hamster.satisfied; // false

set(hamster, 'percentCarrotsEaten', 100);
hamster.satisfied; // true

set(hamster, 'percentCarrotsEaten', 50);
hamster.satisfied; // false

Classic Class Example:

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

let Hamster = EmberObject.extend({
  satisfied: equal('percentCarrotsEaten', 100)
});

let hamster = Hamster.create();

hamster.satisfied; // false

set(hamster, 'percentCarrotsEaten', 100);
hamster.satisfied; // true

set(hamster, 'percentCarrotsEaten', 50);
hamster.satisfied; // false

expandProperties (pattern, callback) public

Module: @ember/object
import { expandProperties } from '@ember/object/computed';
pattern
String
The property pattern to expand.
callback
Function
The callback to invoke. It is invoked once per expansion, and is passed the expansion.

Expands pattern, invoking callback for each expansion.

The only pattern supported is brace-expansion, anything else will be passed once to callback directly.

Example

import { expandProperties } from '@ember/object/computed';

function echo(arg){ console.log(arg); }

expandProperties('foo.bar', echo);              //=> 'foo.bar'
expandProperties('{foo,bar}', echo);            //=> 'foo', 'bar'
expandProperties('foo.{bar,baz}', echo);        //=> 'foo.bar', 'foo.baz'
expandProperties('{foo,bar}.baz', echo);        //=> 'foo.baz', 'bar.baz'
expandProperties('foo.{bar,baz}.[]', echo)      //=> 'foo.bar.[]', 'foo.baz.[]'
expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs'
expandProperties('{foo}.bar.{baz}')             //=> 'foo.bar.baz'

filter (dependentKey, additionalDependentKeys, callback) ComputedProperty public

Module: @ember/object
import { filter } from '@ember/object/computed';
dependentKey
String
additionalDependentKeys
Array
optional array of additional dependent keys
callback
Function
returns
ComputedProperty
the filtered array

Filters the array by the callback.

The callback method you provide should have the following signature:

  • item is the current item in the iteration.
  • index is the integer index of the current item in the iteration.
  • array is the dependant array itself.
function filterCallback(item, index, array);

Example:

import { set } from '@ember/object';
import { filter } from '@ember/object/computed';

class Hamster {
  constructor(chores) {
    set(this, 'chores', chores);
  }

  @filter('chores', function(chore, index, array) {
    return !chore.done;
  })
  remainingChores;
}

let hamster = Hamster.create([
  { name: 'cook', done: true },
  { name: 'clean', done: true },
  { name: 'write more unit tests', done: false }
]);

hamster.remainingChores; // [{name: 'write more unit tests', done: false}]

Classic Class Example:

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

let Hamster = EmberObject.extend({
  remainingChores: filter('chores', function(chore, index, array) {
    return !chore.done;
  })
});

let hamster = Hamster.create({
  chores: [
    { name: 'cook', done: true },
    { name: 'clean', done: true },
    { name: 'write more unit tests', done: false }
  ]
});

hamster.remainingChores; // [{name: 'write more unit tests', done: false}]

You can also use @each.property in your dependent key, the callback will still use the underlying array:

import { set } from '@ember/object';
import { filter } from '@ember/object/computed';

class Hamster {
  constructor(chores) {
    set(this, 'chores', chores);
  }

  @filter('[email protected]', function(chore, index, array) {
    return !chore.done;
  })
  remainingChores;
}

let hamster = new Hamster([
  { name: 'cook', done: true },
  { name: 'clean', done: true },
  { name: 'write more unit tests', done: false }
]);
hamster.remainingChores; // [{name: 'write more unit tests', done: false}]

set(hamster.chores[2], 'done', true);
hamster.remainingChores; // []

Finally, you can optionally pass an array of additional dependent keys as the second parameter to the macro, if your filter function relies on any external values:

import { filter } from '@ember/object/computed';

class Hamster {
  constructor(chores) {
    set(this, 'chores', chores);
  }

  doneKey = 'finished';

  @filter('chores', ['doneKey'], function(chore, index, array) {
    return !chore[this.doneKey];
  })
  remainingChores;
}

let hamster = new Hamster([
  { name: 'cook', finished: true },
  { name: 'clean', finished: true },
  { name: 'write more unit tests', finished: false }
]);

hamster.remainingChores; // [{name: 'write more unit tests', finished: false}]

filterBy (dependentKey, propertyKey, value) ComputedProperty public

Module: @ember/object
import { filterBy } from '@ember/object/computed';
dependentKey
String
propertyKey
String
value
*
returns
ComputedProperty
the filtered array

Filters the array by the property and value.

Example:

import { set } from '@ember/object';
import { filterBy } from '@ember/object/computed';

class Hamster {
  constructor(chores) {
    set(this, 'chores', chores);
  }

  @filterBy('chores', 'done', false) remainingChores;
}

let hamster = new Hamster([
  { name: 'cook', done: true },
  { name: 'clean', done: true },
  { name: 'write more unit tests', done: false }
]);

hamster.remainingChores; // [{ name: 'write more unit tests', done: false }]

Classic Class Example:

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

let Hamster = EmberObject.extend({
  remainingChores: filterBy('chores', 'done', false)
});

let hamster = Hamster.create({
  chores: [
    { name: 'cook', done: true },
    { name: 'clean', done: true },
    { name: 'write more unit tests', done: false }
  ]
});

hamster.remainingChores; // [{ name: 'write more unit tests', done: false }]

gt (dependentKey, value) ComputedProperty public

Module: @ember/object
import { gt } from '@ember/object/computed';
dependentKey
String
value
Number
returns
ComputedProperty
computed property which returns true if the original value for property is greater than given value.

A computed property that returns true if the provided dependent property is greater than the provided value.

Example:

import { set } from '@ember/object';
import { gt } from '@ember/object/computed';

class Hamster {
  @gt('numBananas', 10) hasTooManyBananas;
}

let hamster = new Hamster();

hamster.hasTooManyBananas; // false

set(hamster, 'numBananas', 3);
hamster.hasTooManyBananas; // false

set(hamster, 'numBananas', 11);
hamster.hasTooManyBananas; // true

Classic Class Example:

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

let Hamster = EmberObject.extend({
  hasTooManyBananas: gt('numBananas', 10)
});

let hamster = Hamster.create();

hamster.hasTooManyBananas; // false

set(hamster, 'numBananas', 3);
hamster.hasTooManyBananas; // false

set(hamster, 'numBananas', 11);
hamster.hasTooManyBananas; // true

gte (dependentKey, value) ComputedProperty public

Module: @ember/object
import { gte } from '@ember/object/computed';
dependentKey
String
value
Number
returns
ComputedProperty
computed property which returns true if the original value for property is greater or equal then given value.

A computed property that returns true if the provided dependent property is greater than or equal to the provided value.

Example:

import { set } from '@ember/object';
import { gte } from '@ember/object/computed';

class Hamster {
  @gte('numBananas', 10) hasTooManyBananas;
}

let hamster = new Hamster();

hamster.hasTooManyBananas; // false

set(hamster, 'numBananas', 3);
hamster.hasTooManyBananas; // false

set(hamster, 'numBananas', 10);
hamster.hasTooManyBananas; // true

Classic Class Example:

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

let Hamster = EmberObject.extend({
  hasTooManyBananas: gte('numBananas', 10)
});

let hamster = Hamster.create();

hamster.hasTooManyBananas; // false

set(hamster, 'numBananas', 3);
hamster.hasTooManyBananas; // false

set(hamster, 'numBananas', 10);
hamster.hasTooManyBananas; // true

intersect (propertyKey) ComputedProperty public

Module: @ember/object
import { intersect } from '@ember/object/computed';
propertyKey
String
returns
ComputedProperty
computes a new array with all the duplicated elements from the dependent arrays

A computed property which returns a new array with all the elements two or more dependent arrays have in common.

Example:

import { set } from '@ember/object';
import { intersect } from '@ember/object/computed';

class FriendGroups {
  constructor(adaFriends, charlesFriends) {
    set(this, 'adaFriends', adaFriends);
    set(this, 'charlesFriends', charlesFriends);
  }

  @intersect('adaFriends', 'charlesFriends') friendsInCommon;
}

let groups = new FriendGroups(
  ['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'],
  ['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock']
);

groups.friendsInCommon; // ['William King', 'Mary Somerville']

Classic Class Example:

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

let FriendGroups = EmberObject.extend({
  friendsInCommon: intersect('adaFriends', 'charlesFriends')
});

let groups = FriendGroups.create({
  adaFriends: ['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'],
  charlesFriends: ['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock']
});

groups.friendsInCommon; // ['William King', 'Mary Somerville']

lt (dependentKey, value) ComputedProperty public

Module: @ember/object
import { lt } from '@ember/object/computed';
dependentKey
String
value
Number
returns
ComputedProperty
computed property which returns true if the original value for property is less then given value.

A computed property that returns true if the provided dependent property is less than the provided value.

Example:

import { set } from '@ember/object';
import { lt } from '@ember/object/computed';

class Hamster {
  @lt('numBananas', 3) needsMoreBananas;
}

let hamster = new Hamster();

hamster.needsMoreBananas; // true

set(hamster, 'numBananas', 3);
hamster.needsMoreBananas; // false

set(hamster, 'numBananas', 2);
hamster.needsMoreBananas; // true

Classic Class Example:

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

let Hamster = EmberObject.extend({
  needsMoreBananas: lt('numBananas', 3)
});

let hamster = Hamster.create();

hamster.needsMoreBananas; // true

set(hamster, 'numBananas', 3);
hamster.needsMoreBananas; // false

set(hamster, 'numBananas', 2);
hamster.needsMoreBananas; // true

lte (dependentKey, value) ComputedProperty public

Module: @ember/object
import { lte } from '@ember/object/computed';
dependentKey
String
value
Number
returns
ComputedProperty
computed property which returns true if the original value for property is less or equal than given value.

A computed property that returns true if the provided dependent property is less than or equal to the provided value.

Example:

import { set } from '@ember/object';
import { lte } from '@ember/object/computed';

class Hamster {
  @lte('numBananas', 3) needsMoreBananas;
}

let hamster = new Hamster();

hamster.needsMoreBananas; // true

set(hamster, 'numBananas', 5);
hamster.needsMoreBananas; // false

set(hamster, 'numBananas', 3);
hamster.needsMoreBananas; // true

Classic Class Example:

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

let Hamster = EmberObject.extend({
  needsMoreBananas: lte('numBananas', 3)
});

let hamster = Hamster.create();

hamster.needsMoreBananas; // true

set(hamster, 'numBananas', 5);
hamster.needsMoreBananas; // false

set(hamster, 'numBananas', 3);
hamster.needsMoreBananas; // true

map (dependentKey, additionalDependentKeys, callback) ComputedProperty public

Module: @ember/object
import { map } from '@ember/object/computed';
dependentKey
String
additionalDependentKeys
Array
optional array of additional dependent keys
callback
Function
returns
ComputedProperty
an array mapped via the callback

Returns an array mapped via the callback

The callback method you provide should have the following signature:

  • item is the current item in the iteration.
  • index is the integer index of the current item in the iteration.
function mapCallback(item, index);

Example:

import { set } from '@ember/object';
import { map } from '@ember/object/computed';

class Hamster {
  constructor(chores) {
    set(this, 'chores', chores);
  }

  @map('chores', function(chore, index) {
    return `${chore.toUpperCase()}!`;
  })
  excitingChores;
});

let hamster = new Hamster(['clean', 'write more unit tests']);

hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!']

Classic Class Example:

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

let Hamster = EmberObject.extend({
  excitingChores: map('chores', function(chore, index) {
    return `${chore.toUpperCase()}!`;
  })
});

let hamster = Hamster.create({
  chores: ['clean', 'write more unit tests']
});

hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!']

You can optionally pass an array of additional dependent keys as the second parameter to the macro, if your map function relies on any external values:

import { set } from '@ember/object';
import { map } from '@ember/object/computed';

class Hamster {
  shouldUpperCase = false;

  constructor(chores) {
    set(this, 'chores', chores);
  }

  @map('chores', ['shouldUpperCase'], function(chore, index) {
    if (this.shouldUpperCase) {
      return `${chore.toUpperCase()}!`;
    } else {
      return `${chore}!`;
    }
  })
  excitingChores;
}

let hamster = new Hamster(['clean', 'write more unit tests']);

hamster.excitingChores; // ['clean!', 'write more unit tests!']

set(hamster, 'shouldUpperCase', true);
hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!']

mapBy (dependentKey, propertyKey) ComputedProperty public

Module: @ember/object
import { mapBy } from '@ember/object/computed';
dependentKey
String
propertyKey
String
returns
ComputedProperty
an array mapped to the specified key

Returns an array mapped to the specified key.

Example:

import { set } from '@ember/object';
import { mapBy } from '@ember/object/computed';

class Person {
  children = [];

  @mapBy('children', 'age') childAges;
}

let lordByron = new Person();

lordByron.childAges; // []

set(lordByron, 'children', [
  {
    name: 'Augusta Ada Byron',
    age: 7
  }
]);
lordByron.childAges; // [7]

set(lordByron, 'children', [
  ...lordByron.children,
  {
    name: 'Allegra Byron',
    age: 5
  }, {
    name: 'Elizabeth Medora Leigh',
    age: 8
  }
]);
lordByron.childAges; // [7, 5, 8]

Classic Class Example:

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

let Person = EmberObject.extend({
  childAges: mapBy('children', 'age')
});

let lordByron = Person.create({ children: [] });

lordByron.childAges; // []

set(lordByron, 'children', [
  {
    name: 'Augusta Ada Byron',
    age: 7
  }
]);
lordByron.childAges; // [7]

set(lordByron, 'children', [
  ...lordByron.children,
  {
    name: 'Allegra Byron',
    age: 5
  }, {
    name: 'Elizabeth Medora Leigh',
    age: 8
  }
]);
lordByron.childAges; // [7, 5, 8]

match (dependentKey, regexp) ComputedProperty public

Module: @ember/object
import { match } from '@ember/object/computed';
dependentKey
String
regexp
RegExp
returns
ComputedProperty
computed property which match the original value for property against a given RegExp

A computed property which matches the original value for the dependent property against a given RegExp, returning true if the value matches the RegExp and false if it does not.

Example:

import { set } from '@ember/object';
import { match } from '@ember/object/computed';

class User {
  @match('email', /^.+@.+\..+$/) hasValidEmail;
}

let user = new User();

user.hasValidEmail; // false

set(user, 'email', '');
user.hasValidEmail; // false

set(user, 'email', '[email protected]');
user.hasValidEmail; // true

Classic Class Example:

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

let User = EmberObject.extend({
  hasValidEmail: match('email', /^.+@.+\..+$/)
});

let user = User.create();

user.hasValidEmail; // false

set(user, 'email', '');
user.hasValidEmail; // false

set(user, 'email', '[email protected]');
user.hasValidEmail; // true

max (dependentKey) ComputedProperty public

Module: @ember/object
import { max } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computes the largest value in the dependentKey's array

A computed property that calculates the maximum value in the dependent array. This will return -Infinity when the dependent array is empty.

Example:

import { set } from '@ember/object';
import { mapBy, max } from '@ember/object/computed';

class Person {
  children = [];

  @mapBy('children', 'age') childAges;
  @max('childAges') maxChildAge;
}

let lordByron = new Person();

lordByron.maxChildAge; // -Infinity

set(lordByron, 'children', [
  {
    name: 'Augusta Ada Byron',
    age: 7
  }
]);
lordByron.maxChildAge; // 7

set(lordByron, 'children', [
  ...lordByron.children,
  {
    name: 'Allegra Byron',
    age: 5
  }, {
    name: 'Elizabeth Medora Leigh',
    age: 8
  }
]);
lordByron.maxChildAge; // 8

Classic Class Example:

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

let Person = EmberObject.extend({
  childAges: mapBy('children', 'age'),
  maxChildAge: max('childAges')
});

let lordByron = Person.create({ children: [] });

lordByron.maxChildAge; // -Infinity

set(lordByron, 'children', [
  {
    name: 'Augusta Ada Byron',
    age: 7
  }
]);
lordByron.maxChildAge; // 7

set(lordByron, 'children', [
  ...lordByron.children,
  {
    name: 'Allegra Byron',
    age: 5
  }, {
    name: 'Elizabeth Medora Leigh',
    age: 8
  }
]);
lordByron.maxChildAge; // 8

If the types of the arguments are not numbers, they will be converted to numbers and the type of the return value will always be Number. For example, the max of a list of Date objects will be the highest timestamp as a Number. This behavior is consistent with Math.max.

min (dependentKey) ComputedProperty public

Module: @ember/object
import { min } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computes the smallest value in the dependentKey's array

A computed property that calculates the minimum value in the dependent array. This will return Infinity when the dependent array is empty.

Example:

import { set } from '@ember/object';
import { mapBy, min } from '@ember/object/computed';

class Person {
  children = [];

  @mapBy('children', 'age') childAges;
  @min('childAges') minChildAge;
}

let lordByron = Person.create({ children: [] });

lordByron.minChildAge; // Infinity

set(lordByron, 'children', [
  {
    name: 'Augusta Ada Byron',
    age: 7
  }
]);
lordByron.minChildAge; // 7

set(lordByron, 'children', [
  ...lordByron.children,
  {
    name: 'Allegra Byron',
    age: 5
  }, {
    name: 'Elizabeth Medora Leigh',
    age: 8
  }
]);
lordByron.minChildAge; // 5

Classic Class Example:

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

let Person = EmberObject.extend({
  childAges: mapBy('children', 'age'),
  minChildAge: min('childAges')
});

let lordByron = Person.create({ children: [] });

lordByron.minChildAge; // Infinity

set(lordByron, 'children', [
  {
    name: 'Augusta Ada Byron',
    age: 7
  }
]);
lordByron.minChildAge; // 7

set(lordByron, 'children', [
  ...lordByron.children,
  {
    name: 'Allegra Byron',
    age: 5
  }, {
    name: 'Elizabeth Medora Leigh',
    age: 8
  }
]);
lordByron.minChildAge; // 5

If the types of the arguments are not numbers, they will be converted to numbers and the type of the return value will always be Number. For example, the min of a list of Date objects will be the lowest timestamp as a Number. This behavior is consistent with Math.min.

none (dependentKey) ComputedProperty public

Module: @ember/object
import { none } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which returns true if original value for property is null or undefined.

A computed property that returns true if the value of the dependent property is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing.

import { set } from '@ember/object';
import { none } from '@ember/object/computed';

class Hamster {
  @none('food') isHungry;
}

let hamster = new Hamster();

hamster.isHungry; // true

set(hamster, 'food', 'Banana');
hamster.isHungry; // false

set(hamster, 'food', null);
hamster.isHungry; // true

Classic Class Example:

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

let Hamster = EmberObject.extend({
  isHungry: none('food')
});

let hamster = Hamster.create();

hamster.isHungry; // true

set(hamster, 'food', 'Banana');
hamster.isHungry; // false

set(hamster, 'food', null);
hamster.isHungry; // true

not (dependentKey) ComputedProperty public

Module: @ember/object
import { not } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which returns inverse of the original value for property

A computed property that returns the inverse boolean value of the original value for the dependent property.

Example:

import { set } from '@ember/object';
import { not } from '@ember/object/computed';

class User {
  loggedIn = false;

  @not('loggedIn') isAnonymous;
}

let user = new User();

user.isAnonymous; // true
set(user, 'loggedIn', true);
user.isAnonymous; // false

Classic Class Example:

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

let User = EmberObject.extend({
  loggedIn: false,

  isAnonymous: not('loggedIn')
});

let user = User.create();

user.isAnonymous; // true
set(user, 'loggedIn', true);
user.isAnonymous; // false

notEmpty (dependentKey) ComputedProperty public

Module: @ember/object
import { notEmpty } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which returns true if original value for property is not empty.

A computed property that returns true if the value of the dependent property is NOT null, an empty string, empty array, or empty function.

Example:

import { set } from '@ember/object';
import { notEmpty } from '@ember/object/computed';

class Hamster {
  constructor(backpack) {
    set(this, 'backpack', backpack);
  }

  @notEmpty('backpack') hasStuff
}

let hamster = new Hamster(
  ['Food', 'Sleeping Bag', 'Tent']
);

hamster.hasStuff; // true
set(hamster, 'backpack', []);
hamster.hasStuff; // false

Classic Class Example:

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

let Hamster = EmberObject.extend({
  hasStuff: notEmpty('backpack')
});

let hamster = Hamster.create({
  backpack: ['Food', 'Sleeping Bag', 'Tent']
});

hamster.hasStuff; // true
set(hamster, 'backpack', []);
hamster.hasStuff; // false

oneWay (dependentKey) ComputedProperty public

Module: @ember/object
import { oneWay } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which creates a one way computed property to the original value for property.

Where computed.alias aliases get and set, and allows for bidirectional data flow, computed.oneWay only provides an aliased get. The set will not mutate the upstream property, rather causes the current property to become the value set. This causes the downstream property to permanently diverge from the upstream property.

Example:

import { set } from '@ember/object';
import { oneWay }from '@ember/object/computed';

class User {
  constructor(firstName, lastName) {
    set(this, 'firstName', firstName);
    set(this, 'lastName', lastName);
  }

  @oneWay('firstName') nickName;
}

let teddy = new User('Teddy', 'Zeenny');

teddy.nickName; // 'Teddy'

set(teddy, 'nickName', 'TeddyBear');
teddy.firstName; // 'Teddy'
teddy.nickName; // 'TeddyBear'

Classic Class Example:

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

let User = EmberObject.extend({
  firstName: null,
  lastName: null,

  nickName: oneWay('firstName')
});

let teddy = User.create({
  firstName: 'Teddy',
  lastName: 'Zeenny'
});

teddy.nickName; // 'Teddy'

set(teddy, 'nickName', 'TeddyBear'); // 'TeddyBear'
teddy.firstName; // 'Teddy'
teddy.nickName; // 'TeddyBear'

or (dependentKey) ComputedProperty public

Module: @ember/object
import { or } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which performs a logical `or` on the values of all the original values for properties.

A computed property which performs a logical or on the original values for the provided dependent properties.

You may pass in more than two properties and even use property brace expansion. The computed property will return the first truthy value or last falsy value just like JavaScript's || operator.

Example:

import { set } from '@ember/object';
import { or } from '@ember/object/computed';

class Hamster {
  @or('hasJacket', 'hasUmbrella') readyForRain;
  @or('hasSunscreen', 'hasUmbrella') readyForBeach;
}

let tomster = new Hamster();

tomster.readyForRain; // undefined

set(tomster, 'hasUmbrella', true);
tomster.readyForRain; // true

set(tomster, 'hasJacket', 'Yes');
tomster.readyForRain; // 'Yes'

set(tomster, 'hasSunscreen', 'Check');
tomster.readyForBeach; // 'Check'

Classic Class Example:

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

let Hamster = EmberObject.extend({
  readyForRain: or('hasJacket', 'hasUmbrella'),
  readyForBeach: or('hasSunscreen', 'hasUmbrella')
});

let tomster = Hamster.create();

tomster.readyForRain; // undefined

set(tomster, 'hasUmbrella', true);
tomster.readyForRain; // true

set(tomster, 'hasJacket', 'Yes');
tomster.readyForRain; // 'Yes'

set(tomster, 'hasSunscreen', 'Check');
tomster.readyForBeach; // 'Check'

readOnly (dependentKey) ComputedProperty public

Module: @ember/object

Available since v1.5.0

import { readOnly } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which creates a one way computed property to the original value for property.

Where computed.oneWay provides oneWay bindings, computed.readOnly provides a readOnly one way binding. Very often when using computed.oneWay one does not also want changes to propagate back up, as they will replace the value.

This prevents the reverse flow, and also throws an exception when it occurs.

Example:

import { set } from '@ember/object';
import { readOnly } from '@ember/object/computed';

class User {
  constructor(firstName, lastName) {
    set(this, 'firstName', firstName);
    set(this, 'lastName', lastName);
  }

  @readOnly('firstName') nickName;
});

let teddy = new User('Teddy', 'Zeenny');

teddy.nickName; // 'Teddy'

set(teddy, 'nickName', 'TeddyBear'); // throws Exception
// throw new EmberError('Cannot Set: nickName on: <User:ember27288>' );`

teddy.firstName; // 'Teddy'

Classic Class Example:

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

let User = EmberObject.extend({
  firstName: null,
  lastName: null,

  nickName: readOnly('firstName')
});

let teddy = User.create({
  firstName: 'Teddy',
  lastName:  'Zeenny'
});

teddy.nickName; // 'Teddy'

set(teddy, 'nickName', 'TeddyBear'); // throws Exception
// throw new EmberError('Cannot Set: nickName on: <User:ember27288>' );`

teddy.firstName; // 'Teddy'

reads (dependentKey) ComputedProperty public

Module: @ember/object
import { reads } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computed property which creates a one way computed property to the original value for property.

This is a more semantically meaningful alias of computed.oneWay, whose name is somewhat ambiguous as to which direction the data flows.

setDiff (setAProperty, setBProperty) ComputedProperty public

Module: @ember/object
import { setDiff } from '@ember/object/computed';
setAProperty
String
setBProperty
String
returns
ComputedProperty
computes a new array with all the items from the first dependent array that are not in the second dependent array

A computed property which returns a new array with all the properties from the first dependent array that are not in the second dependent array.

Example:

import { set } from '@ember/object';
import { setDiff } from '@ember/object/computed';

class Hamster {
  constructor(likes, fruits) {
    set(this, 'likes', likes);
    set(this, 'fruits', fruits);
  }

  @setDiff('likes', 'fruits') wants;
}

let hamster = new Hamster(
  [
    'banana',
    'grape',
    'kale'
  ],
  [
    'grape',
    'kale',
  ]
);

hamster.wants; // ['banana']

Classic Class Example:

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

let Hamster = EmberObject.extend({
  wants: setDiff('likes', 'fruits')
});

let hamster = Hamster.create({
  likes: [
    'banana',
    'grape',
    'kale'
  ],
  fruits: [
    'grape',
    'kale',
  ]
});

hamster.wants; // ['banana']

sort (itemsKey, sortDefinitionOrDependentKeys, sortDefinition) ComputedProperty public

Module: @ember/object
import { sort } from '@ember/object/computed';
itemsKey
String
sortDefinitionOrDependentKeys
String|Function|Array
The key of the sort definition (an array of sort properties), the sort function, or an array of additional dependent keys
sortDefinition
Function?
the sort function (when used with additional dependent keys)
returns
ComputedProperty
computes a new sorted array based on the sort property array or callback function

A computed property which returns a new array with all the properties from the first dependent array sorted based on a property or sort function. The sort macro can be used in two different ways:

  1. By providing a sort callback function
  2. By providing an array of keys to sort the array

In the first form, the callback method you provide should have the following signature:

function sortCallback(itemA, itemB);
  • itemA the first item to compare.
  • itemB the second item to compare.

This function should return negative number (e.g. -1) when itemA should come before itemB. It should return positive number (e.g. 1) when itemA should come after itemB. If the itemA and itemB are equal this function should return 0.

Therefore, if this function is comparing some numeric values, simple itemA - itemB or itemA.get( 'foo' ) - itemB.get( 'foo' ) can be used instead of series of if.

Example:

import { set } from '@ember/object';
import { sort } from '@ember/object/computed';

class ToDoList {
  constructor(todos) {
    set(this, 'todos', todos);
  }

  // using a custom sort function
  @sort('todos', function(a, b){
    if (a.priority > b.priority) {
      return 1;
    } else if (a.priority < b.priority) {
      return -1;
    }

    return 0;
  })
  priorityTodos;
}

let todoList = new ToDoList([
  { name: 'Unit Test', priority: 2 },
  { name: 'Documentation', priority: 3 },
  { name: 'Release', priority: 1 }
]);

todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]

Classic Class Example:

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

let ToDoList = EmberObject.extend({
  // using a custom sort function
  priorityTodos: sort('todos', function(a, b){
    if (a.priority > b.priority) {
      return 1;
    } else if (a.priority < b.priority) {
      return -1;
    }

    return 0;
  })
});

let todoList = ToDoList.create({
  todos: [
    { name: 'Unit Test', priority: 2 },
    { name: 'Documentation', priority: 3 },
    { name: 'Release', priority: 1 }
  ]
});

todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]

You can also optionally pass an array of additional dependent keys as the second parameter, if your sort function is dependent on additional values that could changes:

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

class ToDoList {
  sortKey = 'priority';

  constructor(todos) {
    set(this, 'todos', todos);
  }

  // using a custom sort function
  @sort('todos', ['sortKey'], function(a, b){
    if (a[this.sortKey] > b[this.sortKey]) {
      return 1;
    } else if (a[this.sortKey] < b[this.sortKey]) {
      return -1;
    }

    return 0;
  })
  sortedTodos;
});

let todoList = new ToDoList([
  { name: 'Unit Test', priority: 2 },
  { name: 'Documentation', priority: 3 },
  { name: 'Release', priority: 1 }
]);

todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]

In the second form, you should provide the key of the array of sort values as the second parameter:

import { set } from '@ember/object';
import { sort } from '@ember/object/computed';

class ToDoList {
  constructor(todos) {
    set(this, 'todos', todos);
  }

  // using standard ascending sort
  todosSorting = ['name'];
  @sort('todos', 'todosSorting') sortedTodos;

  // using descending sort
  todosSortingDesc = ['name:desc'];
  @sort('todos', 'todosSortingDesc') sortedTodosDesc;
}

let todoList = new ToDoList([
  { name: 'Unit Test', priority: 2 },
  { name: 'Documentation', priority: 3 },
  { name: 'Release', priority: 1 }
]);

todoList.sortedTodos; // [{ name:'Documentation', priority:3 }, { name:'Release', priority:1 }, { name:'Unit Test', priority:2 }]
todoList.sortedTodosDesc; // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }]

sum (dependentKey) ComputedProperty public

Module: @ember/object

Available since v1.4.0

import { sum } from '@ember/object/computed';
dependentKey
String
returns
ComputedProperty
computes the sum of all values in the dependentKey's array

A computed property that returns the sum of the values in the dependent array.

Example:

import { sum } from '@ember/object/computed';

class Invoice {
  lineItems = [1.00, 2.50, 9.99];

  @sum('lineItems') total;
}

let invoice = new Invoice();

invoice.total; // 13.49

Classic Class Example:

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

let Invoice = EmberObject.extend({
  lineItems: [1.00, 2.50, 9.99],

  total: sum('lineItems')
})

let invoice = Invoice.create();

invoice.total; // 13.49

union (propertyKey) ComputedProperty public

Module: @ember/object
import { union } from '@ember/object/computed';
propertyKey
String
returns
ComputedProperty
computes a new array with all the unique elements from one or more dependent arrays.

A computed property which returns a new array with all the unique elements from one or more dependent arrays.

Example:

import { set } from '@ember/object';
import { union } from '@ember/object/computed';

class Hamster {
  constructor(fruits, vegetables) {
    set(this, 'fruits', fruits);
    set(this, 'vegetables', vegetables);
  }

  @union('fruits', 'vegetables') uniqueFruits;
});

let hamster = new, Hamster(
  [
    'banana',
    'grape',
    'kale',
    'banana',
    'tomato'
  ],
  [
    'tomato',
    'carrot',
    'lettuce'
  ]
);

hamster.uniqueFruits; // ['banana', 'grape', 'kale', 'tomato', 'carrot', 'lettuce']

Classic Class Example:

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

let Hamster = EmberObject.extend({
  uniqueFruits: union('fruits', 'vegetables')
});

let hamster = Hamster.create({
  fruits: [
    'banana',
    'grape',
    'kale',
    'banana',
    'tomato'
  ],
  vegetables: [
    'tomato',
    'carrot',
    'lettuce'
  ]
});

hamster.uniqueFruits; // ['banana', 'grape', 'kale', 'tomato', 'carrot', 'lettuce']

uniq (propertyKey) ComputedProperty public

Module: @ember/object
import { uniq } from '@ember/object/computed';
propertyKey
String
returns
ComputedProperty
computes a new array with all the unique elements from the dependent array

A computed property which returns a new array with all the unique elements from one or more dependent arrays.

Example:

import { set } from '@ember/object';
import { uniq } from '@ember/object/computed';

class Hamster {
  constructor(fruits) {
    set(this, 'fruits', fruits);
  }

  @uniq('fruits') uniqueFruits;
}

let hamster = new Hamster([
  'banana',
  'grape',
  'kale',
  'banana'
]);

hamster.uniqueFruits; // ['banana', 'grape', 'kale']

Classic Class Example:

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

let Hamster = EmberObject.extend({
  uniqueFruits: uniq('fruits')
});

let hamster = Hamster.create({
  fruits: [
    'banana',
    'grape',
    'kale',
    'banana'
  ]
});

hamster.uniqueFruits; // ['banana', 'grape', 'kale']

uniqBy (dependentKey, propertyKey) ComputedProperty public

Module: @ember/object
import { uniqBy } from '@ember/object/computed';
dependentKey
String
propertyKey
String
returns
ComputedProperty
computes a new array with all the unique elements from the dependent array

A computed property which returns a new array with all the unique elements from an array, with uniqueness determined by specific key.

Example:

import { set } from '@ember/object';
import { uniqBy } from '@ember/object/computed';

class Hamster {
  constructor(fruits) {
    set(this, 'fruits', fruits);
  }

  @uniqBy('fruits', 'id') uniqueFruits;
}

let hamster = new Hamster([
  { id: 1, 'banana' },
  { id: 2, 'grape' },
  { id: 3, 'peach' },
  { id: 1, 'banana' }
]);

hamster.uniqueFruits; // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }]

Classic Class Example:

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

let Hamster = EmberObject.extend({
  uniqueFruits: uniqBy('fruits', 'id')
});

let hamster = Hamster.create({
  fruits: [
    { id: 1, 'banana' },
    { id: 2, 'grape' },
    { id: 3, 'peach' },
    { id: 1, 'banana' }
  ]
});

hamster.uniqueFruits; // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }]

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