Class @ember/object/computed

Module: @ember/object

Show:

Module: @ember/object
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { alias } from '@ember/object/computed';
import EmberObject from '@ember/object';

let Person = EmberObject.extend({
  name: 'Alex Matchneer',
  nomen: alias('name')
});

let alex = Person.create();

alex.get('nomen'); // 'Alex Matchneer'
alex.get('name');  // 'Alex Matchneer'

alex.set('nomen', '@machty');
alex.get('name');  // '@machty'
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { and } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let tomster = Hamster.create();

tomster.get('readyForCamp'); // false
tomster.set('hasTent', true);
tomster.get('readyForCamp'); // false
tomster.set('hasBackpack', true);
tomster.get('readyForCamp'); // true
tomster.set('hasBackpack', 'Yes');
tomster.get('readyForCamp'); // 'Yes'
tomster.set('hasWalkingStick', null);
tomster.get('readyForHike'); // null
Module: @ember/object
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { bool } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create();

hamster.get('hasBananas'); // false
hamster.set('numBananas', 0);
hamster.get('hasBananas'); // false
hamster.set('numBananas', 1);
hamster.get('hasBananas'); // true
hamster.set('numBananas', null);
hamster.get('hasBananas'); // false
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
import { collect } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create();

hamster.get('clothes'); // [null, null]
hamster.set('hat', 'Camp Hat');
hamster.set('shirt', 'Camp Shirt');
hamster.get('clothes'); // ['Camp Hat', 'Camp Shirt']
Module: @ember/object

Available since v1.7.0

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { deprecatingAlias } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create();

hamster.set('bananaCount', 5); // Prints a deprecation warning.
hamster.get('cavendishCount'); // 5
Module: @ember/object

Available since v1.6.0

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 that returns true if the value of the dependent property is null, an empty string, empty array, or empty function.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { empty } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

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

todoList.get('isDone'); // false
todoList.get('todos').clear();
todoList.get('isDone'); // true
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { equal } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create();

hamster.get('satisfied'); // false
hamster.set('percentCarrotsEaten', 100);
hamster.get('satisfied'); // true
hamster.set('percentCarrotsEaten', 50);
hamster.get('satisfied'); // false
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
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'
Module: @ember/object
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.

1
function(item, index, array);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { filter } from '@ember/object/computed';
import EmberObject from '@ember/object';

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.get('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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { A } from '@ember/array';
import { filter } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create({
  chores: A([
    EmberObject.create({ name: 'cook', done: true }),
    EmberObject.create({ name: 'clean', done: true }),
    EmberObject.create({ name: 'write more unit tests', done: false })
  ])
});
hamster.get('remainingChores'); // [{name: 'write more unit tests', done: false}]
hamster.get('chores').objectAt(2).set('done', true);
hamster.get('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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { filter } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create({
  doneKey: 'finished'

  chores: [
    { name: 'cook', finished: true },
    { name: 'clean', finished: true },
    { name: 'write more unit tests', finished: false }
  ]
});

hamster.get('remainingChores'); // [{name: 'write more unit tests', finished: false}]
Module: @ember/object
dependentKey
String
propertyKey
String
value
*
returns
ComputedProperty
the filtered array

Filters the array by the property and value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { filterBy } from '@ember/object/computed';
import EmberObject from '@ember/object';

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.get('remainingChores'); // [{ name: 'write more unit tests', done: false }]
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { gt } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create();

hamster.get('hasTooManyBananas'); // false
hamster.set('numBananas', 3);
hamster.get('hasTooManyBananas'); // false
hamster.set('numBananas', 11);
hamster.get('hasTooManyBananas'); // true
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { gte } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create();

hamster.get('hasTooManyBananas'); // false
hamster.set('numBananas', 3);
hamster.get('hasTooManyBananas'); // false
hamster.set('numBananas', 10);
hamster.get('hasTooManyBananas'); // true
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
import { intersect } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

obj.get('friendsInCommon'); // ['William King', 'Mary Somerville']
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { lt } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create();

hamster.get('needsMoreBananas'); // true
hamster.set('numBananas', 3);
hamster.get('needsMoreBananas'); // false
hamster.set('numBananas', 2);
hamster.get('needsMoreBananas'); // true
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { lte } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create();

hamster.get('needsMoreBananas'); // true
hamster.set('numBananas', 5);
hamster.get('needsMoreBananas'); // false
hamster.set('numBananas', 3);
hamster.get('needsMoreBananas'); // true
Module: @ember/object
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.

1
function(item, index);

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { map } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

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

hamster.get('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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { map } from '@ember/object/computed';
import EmberObject from '@ember/object';

let Hamster = EmberObject.extend({
  excitingChores: map('chores', ['shouldUpperCase'], function(chore, index) {
    if (this.shouldUpperCase) {
      return chore.toUpperCase() + '!';
    } else {
      return chore + '!';
    }
  })
});

let hamster = Hamster.create({
  shouldUpperCase: false,

  chores: ['clean', 'write more unit tests']
});

hamster.get('excitingChores'); // ['clean!', 'write more unit tests!']
hamster.set('shouldUpperCase', true);
hamster.get('excitingChores'); // ['CLEAN!', 'WRITE MORE UNIT TESTS!']
Module: @ember/object
dependentKey
String
propertyKey
String
returns
ComputedProperty
an array mapped to the specified key

Returns an array mapped to the specified key.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { mapBy } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

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

lordByron.get('childAges'); // []
lordByron.get('children').pushObject({ name: 'Augusta Ada Byron', age: 7 });
lordByron.get('childAges'); // [7]
lordByron.get('children').pushObjects([{
  name: 'Allegra Byron',
  age: 5
}, {
  name: 'Elizabeth Medora Leigh',
  age: 8
}]);
lordByron.get('childAges'); // [7, 5, 8]
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { match } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let user = User.create({loggedIn: false});

user.get('hasValidEmail'); // false
user.set('email', '');
user.get('hasValidEmail'); // false
user.set('email', 'ember_hamster@example.com');
user.get('hasValidEmail'); // true
Module: @ember/object
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { mapBy, max } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

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

lordByron.get('maxChildAge'); // -Infinity
lordByron.get('children').pushObject({
  name: 'Augusta Ada Byron', age: 7
});
lordByron.get('maxChildAge'); // 7
lordByron.get('children').pushObjects([{
  name: 'Allegra Byron',
  age: 5
}, {
  name: 'Elizabeth Medora Leigh',
  age: 8
}]);
lordByron.get('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.

Module: @ember/object
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { mapBy, min } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

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

lordByron.get('minChildAge'); // Infinity
lordByron.get('children').pushObject({
  name: 'Augusta Ada Byron', age: 7
});
lordByron.get('minChildAge'); // 7
lordByron.get('children').pushObjects([{
  name: 'Allegra Byron',
  age: 5
}, {
  name: 'Elizabeth Medora Leigh',
  age: 8
}]);
lordByron.get('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.

Module: @ember/object
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.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { none } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let hamster = Hamster.create();

hamster.get('isHungry'); // true
hamster.set('food', 'Banana');
hamster.get('isHungry'); // false
hamster.set('food', null);
hamster.get('isHungry'); // true
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
import { not } from '@ember/object/computed';
import EmberObject from '@ember/object';

let User = EmberObject.extend({
  isAnonymous: not('loggedIn')
});

let user = User.create({loggedIn: false});

user.get('isAnonymous'); // true
user.set('loggedIn', true);
user.get('isAnonymous'); // false
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
import { notEmpty } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

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

hamster.get('hasStuff');         // true
hamster.get('backpack').clear(); // []
hamster.get('hasStuff');         // false
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { oneWay } from '@ember/object/computed';
import EmberObject from '@ember/object';

let User = EmberObject.extend({
  firstName: null,
  lastName: null,
  nickName: oneWay('firstName')
});

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

teddy.get('nickName');              // 'Teddy'
teddy.set('nickName', 'TeddyBear'); // 'TeddyBear'
teddy.get('firstName');             // 'Teddy'
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { or } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

let tomster = Hamster.create();

tomster.get('readyForRain'); // undefined
tomster.set('hasUmbrella', true);
tomster.get('readyForRain'); // true
tomster.set('hasJacket', 'Yes');
tomster.get('readyForRain'); // 'Yes'
tomster.set('hasSunscreen', 'Check');
tomster.get('readyForBeach'); // 'Check'
Module: @ember/object

Available since v1.5.0

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { readOnly } from '@ember/object/computed';
import EmberObject from '@ember/object';

let User = EmberObject.extend({
  firstName: null,
  lastName: null,
  nickName: readOnly('firstName')
});

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

teddy.get('nickName');              // 'Teddy'
teddy.set('nickName', 'TeddyBear'); // throws Exception
// throw new EmberError('Cannot Set: nickName on: <User:ember27288>' );`
teddy.get('firstName');             // 'Teddy'
Module: @ember/object
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.

Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { setDiff } from '@ember/object/computed';
import EmberObject from '@ember/object';

let Hamster = EmberObject.extend({
  likes: ['banana', 'grape', 'kale'],
  wants: setDiff('likes', 'fruits')
});

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

hamster.get('wants'); // ['banana']
Module: @ember/object
itemsKey
String
additionalDependentKeys
Array
optional array of additional dependent keys
sortDefinition
String or Function
a dependent key to an array of sort properties (add `:desc` to the arrays sort properties to sort descending) or a function to use when sorting
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:

1
function(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

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
import { sort } from '@ember/object/computed';
import EmberObject from '@ember/object';

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.get('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:

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
26
27
import { sort } from '@ember/object/computed';
import EmberObject from '@ember/object';

let ToDoList = EmberObject.extend({
  // using a custom sort function
  sortedTodos: 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;
  })
});

let todoList = ToDoList.create({
  sortKey: 'priority',

  todos: [
    { name: 'Unit Test', priority: 2 },
    { name: 'Documentation', priority: 3 },
    { name: 'Release', priority: 1 }
  ]
});

todoList.get('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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { sort } from '@ember/object/computed';
import EmberObject from '@ember/object';

let ToDoList = EmberObject.extend({
  // using standard ascending sort
  todosSorting: Object.freeze(['name']),
  sortedTodos: sort('todos', 'todosSorting'),

  // using descending sort
  todosSortingDesc: Object.freeze(['name:desc']),
  sortedTodosDesc: sort('todos', 'todosSortingDesc'),
});

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

todoList.get('sortedTodos');      // [{ name:'Documentation', priority:3 }, { name:'Release', priority:1 }, { name:'Unit Test', priority:2 }]
todoList.get('sortedTodosDesc');  // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }]
Module: @ember/object

Available since v1.4.0

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.

Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { union } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

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

hamster.get('uniqueFruits'); // ['banana', 'grape', 'kale', 'tomato', 'carrot', 'lettuce']
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { uniq } from '@ember/object/computed';
import EmberObject from '@ember/object';

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

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

hamster.get('uniqueFruits'); // ['banana', 'grape', 'kale']
Module: @ember/object
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { uniqBy } from '@ember/object/computed';
import EmberObject from '@ember/object';

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.get('uniqueFruits'); // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }]