Ember.computed.* is your friend!

Posted on

I recently got turned on to a much more readable method for writing computed properties in Ember with CoffeeScript by way of Alex Speller’s talk at this year’s EmberFest, The mistakes everyone makes with Ember.JS - Avoiding Common Pitfalls. I had previously been writing computed properties like this:

  foo: (->

Which works out just fine, but it’s much more readable to take this same idea and turn it into this:

  foo: Em.computed 'bar', ->

This new method of writing computed properties made me investigate the Ember namespace documentation, which opened my eyes to a ton of shorthand helpers for computed properties. There are tons of great shorthand methods to do simple computed property calculations that you should be utilizing. I highly recommend that you look at the documentation, but here are a few to get you excited.

Greater Than Comparisons


  isElementGreater: Em.computed 'value', ->
    @get('value') > 10


  isElementGreater: Em.computed.gt 'value', 10

Logical ‘Or’


  orAllTheThings: Em.computed 'value1', 'value2', 'value3' ->
    @get('value1') || @get('value2') || @get('value3')


  orAllTheThings: Em.computed.or 'value1', 'value2', 'value3'



  arrIntersect: Em.computed 'arr1', 'arr2', ->
    # utilize lodash/underscore
    # or (gasp) write it yourself
    _.intersection(@get('arr1'), @get('arr2'))


  arrIntersect: Em.computed.intersect 'arr1', 'arr2'

Read the Docs!

Seriously, have a look at the Ember namespace documentation. Only write a custom computed property when you’re doing something really interesting. Otherwise, let the framework do the heavy lifting.

Find an issue?
Open a pull request against my blog on GitHub.
Ben Limmer