DRY Your Ember Code with Ember.computed Macros

Ember.js is a very expressive framework that allows for more than one way to implement a feature. Ember computed properties are frequently used, but this can sometimes lead to code that is repetitive.

One of my favorite ways for drying up ember code is to use the macros in the Ember.computed module. There are macros that allow for a lot of basic operations, equality, comparisons, and checking for empty lists, just to name a few. The macros are not mentioned in the ember docs, but can be found in ember-metal’s computed object.

Here is an example of a few Ember.computed macros in use:

var TestObject = Ember.Object.extend({
    emptyList: [],
    number: 25,
    prop1: true,
    prop2: false,
    prop3: true,
    
    prop1And3: Ember.computed.and("prop1", "prop3"), // true
    prop1Or2: Ember.computed.or("prop1", "prop2"), // true
    emptyListIsEmpty: Ember.computed.empty("emptyList"), // true
    emptyListNotEmpty: Ember.computed.notEmpty("emptyList"), // false
    numberIs25: Ember.computed.equal("number", 25), // true
    numberBiggerThan50: Ember.computed.gt("number", 50), // false
    propArray: Ember.computed.map("prop1", "prop2", "prop3") // [true,false,true]
    
});