RSSAmplifier

BenLimmer.com · Oct 28, 2014

Ember.computed.* is your friend!

0
Sign in to vote or save

Ben Limmer · BenLimmer.com

Posted on October 28, 2014 by Ben Limmer Avatar image of Ben Limmer

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.

Read the original on benlimmer.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.