Should use computed macrosJS-0812
ember
It is preferred to use Ember's computed property macros as opposed to manually writing out logic in a computed property function. Reasons include:
- Conciseness
- Readability
- Reduced chance of typos
- Reduced chance of missing dependencies
Bad Practice
import Component from '@ember/component';
import { computed } from '@ember/object';
export default Component.extend({
propReads: computed('x', function () {
return this.x;
}),
propAnd: computed('x', 'y', function () {
return this.x && this.y;
}),
propOr: computed('x', 'y', function () {
return this.x || this.y;
}),
propGt: computed('x', function () {
return this.x > 123;
}),
propGte: computed('x', function () {
return this.x >= 123;
}),
propLt: computed('x', function () {
return this.x < 123;
}),
propLte: computed('x', function () {
return this.x <= 123;
}),
propNot: computed('x', function () {
return !this.x;
}),
propEqual: computed('x', function () {
return this.x === 123;
}),
propFilterBy: computed('[email protected]', function () {
return this.chores.filterBy('done', true);
}),
propMapBy: computed('[email protected]', function () {
return this.children.mapBy('age');
})
});
Recommended
import Component from '@ember/component';
import {
reads,
and,
or,
gt,
gte,
lt,
lte,
not,
equal,
filterBy,
mapBy
} from '@ember/object/computed';
export default Component.extend({
propReads: reads('x'),
propAnd: and('x', 'y'),
propOr: or('x', 'y'),
propGt: gt('x', 123),
propGte: gte('x', 123),
propLt: lt('x', 123),
propLte: lte('x', 123),
propNot: not('x'),
propEqual: equal('x', 123),
propFilterBy: filterBy('chores', 'done', true),
propMapBy: mapBy('children', 'age')
});