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: (->
    "foo#{@get('bar')}"
  ).property('bar')

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', ->
    "foo#{@get('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

Before:

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

After:

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

Logical ‘Or’

Before:

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

After:

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

Intersections

Before:

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

After:

  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