Ember.computed Class
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')
Constructor
Ember.computed
-
[dependentKeys*]
-
func
Parameters:
Returns:
property descriptor instance
Item Index
Methods
alias
-
dependentKey
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.
let Person = Ember.Object.extend({
name: 'Alex Matchneer',
nomen: Ember.computed.alias('name')
});
let alex = Person.create();
alex.get('nomen'); // 'Alex Matchneer'
alex.get('name'); // 'Alex Matchneer'
alex.set('nomen', '@machty');
alex.get('name'); // '@machty'
Parameters:
-
dependentKey
String
Returns:
computed property which creates an alias to the original value for property.
and
-
dependentKey
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
let Hamster = Ember.Object.extend({
readyForCamp: Ember.computed.and('hasTent', 'hasBackpack'),
readyForHike: Ember.computed.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
Parameters:
-
dependentKey
String multiple
Returns:
computed property which performs
a logical and
on the values of all the original values for properties.
bool
-
dependentKey
A computed property that converts the provided dependent property into a boolean value.
let Hamster = Ember.Object.extend({
hasBananas: Ember.computed.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
Parameters:
-
dependentKey
String
Returns:
computed property which converts to boolean the original value for property
collect
-
dependentKey
A computed property that returns the array of values for the provided dependent properties.
Example
let Hamster = Ember.Object.extend({
clothes: Ember.computed.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']
Parameters:
-
dependentKey
String multiple
Returns:
computed property which maps values of all passed in properties to an array.
deprecatingAlias
-
dependentKey
-
options
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.
let Hamster = Ember.Object.extend({
bananaCount: Ember.computed.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
Parameters:
-
dependentKey
String -
options
ObjectOptions for
Ember.deprecate
.
Returns:
computed property which creates an alias with a deprecation to the original value for property.
empty
-
dependentKey
A computed property that returns true if the value of the dependent property is null, an empty string, empty array, or empty function.
Example
let ToDoList = Ember.Object.extend({
isDone: Ember.computed.empty('todos')
});
let todoList = ToDoList.create({
todos: ['Unit Test', 'Documentation', 'Release']
});
todoList.get('isDone'); // false
todoList.get('todos').clear();
todoList.get('isDone'); // true
Parameters:
-
dependentKey
String
Returns:
computed property which negate the original value for property
equal
-
dependentKey
-
value
A computed property that returns true if the provided dependent property is equal to the given value.
Example
let Hamster = Ember.Object.extend({
napTime: Ember.computed.equal('state', 'sleepy')
});
let hamster = Hamster.create();
hamster.get('napTime'); // false
hamster.set('state', 'sleepy');
hamster.get('napTime'); // true
hamster.set('state', 'hungry');
hamster.get('napTime'); // false
Returns:
computed property which returns true if the original value for property is equal to the given value.
filter
-
dependentKey
-
callback
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(item, index, array);
let Hamster = Ember.Object.extend({
remainingChores: Ember.computed.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}]
Returns:
the filtered array
filterBy
-
dependentKey
-
propertyKey
-
value
Filters the array by the property and value
let Hamster = Ember.Object.extend({
remainingChores: Ember.computed.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 }]
Returns:
the filtered array
gt
-
dependentKey
-
value
A computed property that returns true if the provided dependent property is greater than the provided value.
Example
let Hamster = Ember.Object.extend({
hasTooManyBananas: Ember.computed.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
Parameters:
-
dependentKey
String -
value
Number
Returns:
computed property which returns true if the original value for property is greater than given value.
gte
-
dependentKey
-
value
A computed property that returns true if the provided dependent property is greater than or equal to the provided value.
Example
let Hamster = Ember.Object.extend({
hasTooManyBananas: Ember.computed.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
Parameters:
-
dependentKey
String -
value
Number
Returns:
computed property which returns true if the original value for property is greater or equal then given value.
intersect
-
propertyKey
A computed property which returns a new array with all the duplicated elements from two or more dependent arrays.
Example
let obj = Ember.Object.extend({
friendsInCommon: Ember.computed.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']
Parameters:
-
propertyKey
String multiple
Returns:
computes a new array with all the duplicated elements from the dependent arrays
lt
-
dependentKey
-
value
A computed property that returns true if the provided dependent property is less than the provided value.
Example
let Hamster = Ember.Object.extend({
needsMoreBananas: Ember.computed.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
Parameters:
-
dependentKey
String -
value
Number
Returns:
computed property which returns true if the original value for property is less then given value.
lte
-
dependentKey
-
value
A computed property that returns true if the provided dependent property is less than or equal to the provided value.
Example
let Hamster = Ember.Object.extend({
needsMoreBananas: Ember.computed.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
Parameters:
-
dependentKey
String -
value
Number
Returns:
computed property which returns true if the original value for property is less or equal than given value.
map
-
dependentKey
-
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(item, index);
Example
let Hamster = Ember.Object.extend({
excitingChores: Ember.computed.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!']
Returns:
an array mapped via the callback
mapBy
-
dependentKey
-
propertyKey
Returns an array mapped to the specified key.
let Person = Ember.Object.extend({
childAges: Ember.computed.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]
Returns:
an array mapped to the specified key
match
-
dependentKey
-
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
let User = Ember.Object.extend({
hasValidEmail: Ember.computed.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
Parameters:
-
dependentKey
String -
regexp
RegExp
Returns:
computed property which match the original value for property against a given RegExp
max
-
dependentKey
A computed property that calculates the maximum value in the
dependent array. This will return -Infinity
when the dependent
array is empty.
let Person = Ember.Object.extend({
childAges: Ember.computed.mapBy('children', 'age'),
maxChildAge: Ember.computed.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
.
Parameters:
-
dependentKey
String
Returns:
computes the largest value in the dependentKey's array
min
-
dependentKey
A computed property that calculates the minimum value in the
dependent array. This will return Infinity
when the dependent
array is empty.
let Person = Ember.Object.extend({
childAges: Ember.computed.mapBy('children', 'age'),
minChildAge: Ember.computed.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
.
Parameters:
-
dependentKey
String
Returns:
computes the smallest value in the dependentKey's array
none
-
dependentKey
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
let Hamster = Ember.Object.extend({
isHungry: Ember.computed.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
Parameters:
-
dependentKey
String
Returns:
computed property which returns true if original value for property is null or undefined.
not
-
dependentKey
A computed property that returns the inverse boolean value of the original value for the dependent property.
Example
let User = Ember.Object.extend({
isAnonymous: Ember.computed.not('loggedIn')
});
let user = User.create({loggedIn: false});
user.get('isAnonymous'); // true
user.set('loggedIn', true);
user.get('isAnonymous'); // false
Parameters:
-
dependentKey
String
Returns:
computed property which returns inverse of the original value for property
notEmpty
-
dependentKey
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
let Hamster = Ember.Object.extend({
hasStuff: Ember.computed.notEmpty('backpack')
});
let hamster = Hamster.create({ backpack: ['Food', 'Sleeping Bag', 'Tent'] });
hamster.get('hasStuff'); // true
hamster.get('backpack').clear(); // []
hamster.get('hasStuff'); // false
Parameters:
-
dependentKey
String
Returns:
computed property which returns true if original value for property is not empty.
oneWay
-
dependentKey
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
let User = Ember.Object.extend({
firstName: null,
lastName: null,
nickName: Ember.computed.oneWay('firstName')
});
let teddy = User.create({
firstName: 'Teddy',
lastName: 'Zeenny'
});
teddy.get('nickName'); // 'Teddy'
teddy.set('nickName', 'TeddyBear'); // 'TeddyBear'
teddy.get('firstName'); // 'Teddy'
Parameters:
-
dependentKey
String
Returns:
computed property which creates a one way computed property to the original value for property.
or
-
dependentKey
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
let Hamster = Ember.Object.extend({
readyForRain: Ember.computed.or('hasJacket', 'hasUmbrella'),
readyForBeach: Ember.computed.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'
Parameters:
-
dependentKey
String multiple
Returns:
computed property which performs
a logical or
on the values of all the original values for properties.
readOnly
-
dependentKey
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
let User = Ember.Object.extend({
firstName: null,
lastName: null,
nickName: Ember.computed.readOnly('firstName')
});
let teddy = User.create({
firstName: 'Teddy',
lastName: 'Zeenny'
});
teddy.get('nickName'); // 'Teddy'
teddy.set('nickName', 'TeddyBear'); // throws Exception
// throw new Ember.Error('Cannot Set: nickName on: <User:ember27288>' );`
teddy.get('firstName'); // 'Teddy'
Parameters:
-
dependentKey
String
Returns:
computed property which creates a one way computed property to the original value for property.
reads
-
dependentKey
This is a more semantically meaningful alias of computed.oneWay
,
whose name is somewhat ambiguous as to which direction the data flows.
Parameters:
-
dependentKey
String
Returns:
computed property which creates a one way computed property to the original value for property.
setDiff
-
setAProperty
-
setBProperty
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
let Hamster = Ember.Object.extend({
likes: ['banana', 'grape', 'kale'],
wants: Ember.computed.setDiff('likes', 'fruits')
});
let hamster = Hamster.create({
fruits: [
'grape',
'kale',
]
});
hamster.get('wants'); // ['banana']
Returns:
computes a new array with all the items from the first dependent array that are not in the second dependent array
sort
-
itemsKey
-
sortDefinition
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 callback method you provide should have the following signature:
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
let ToDoList = Ember.Object.extend({
// using standard ascending sort
todosSorting: ['name'],
sortedTodos: Ember.computed.sort('todos', 'todosSorting'),
// using descending sort
todosSortingDesc: ['name:desc'],
sortedTodosDesc: Ember.computed.sort('todos', 'todosSortingDesc'),
// using a custom sort function
priorityTodos: Ember.computed.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('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 }]
todoList.get('priorityTodos'); // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]
Parameters:
-
itemsKey
String -
sortDefinition
String or Functiona 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:
computes a new sorted array based on the sort property array or callback function
sum
-
dependentKey
A computed property that returns the sum of the values in the dependent array.
Parameters:
-
dependentKey
String
Returns:
computes the sum of all values in the dependentKey's array
union
-
propertyKey
Alias for Ember.computed.uniq.
Parameters:
-
propertyKey
String multiple
Returns:
computes a new array with all the unique elements from the dependent array
uniq
-
propertyKey
A computed property which returns a new array with all the unique elements from one or more dependent arrays.
Example
let Hamster = Ember.Object.extend({
uniqueFruits: Ember.computed.uniq('fruits')
});
let hamster = Hamster.create({
fruits: [
'banana',
'grape',
'kale',
'banana'
]
});
hamster.get('uniqueFruits'); // ['banana', 'grape', 'kale']
Parameters:
-
propertyKey
String multiple
Returns:
computes a new array with all the unique elements from the dependent array
uniqBy
-
dependentKey
-
propertyKey
A computed property which returns a new array with all the unique elements from an array, with uniqueness determined by specific key.
Example
let Hamster = Ember.Object.extend({
uniqueFruits: Ember.computed.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' }]
Returns:
computes a new array with all the unique elements from the dependent array