Last Updated: February 25, 2016
·
817
· marclove

Define your own Ember computed property helpers

Ember has some awesome computed property helpers that let you concisely express common computed properties. While writing your app, you may begin to notice some other patterns in your computed properties which can be nicely extracted into your own computed property helpers.

For instance, Ember currently comes with Ember.computed.notEmpty but you might want a notBlank helper too:

MyApp.computed = {
    notBlank: function (dependentKey) {
        return Ember.computed(dependentKey, function() {
            !Ember.isBlank(Ember.get(this, dependentKey));
        }).readOnly();
    }
};

or something more application-specific like translating an enum value:

MyApp.computed = {
    enum: function(serializedKey, enumType) {
        return Ember.computed(serializedKey, function(key, value) {
            if(arguments.length > 1) {
                var serializedValue = MyApp.Enums.serialize(enumType, value);
                Ember.set(this, serializedKey, serializedValue);
                return value;
            } else {
                var serializedValue = Ember.get(this, serializedKey);
                return MyApp.Enums.deserialize(enumType, serializedValue);
            }
         });
     }
};

To dig deeper, check out Ember's implementation of their computed property helpers:
https://github.com/emberjs/ember.js/blob/v1.5.0/packages/ember-metal/lib/computed.js