pangratz prattles

Useful Ember.js Functions

While developing stuff with Ember.js I stumbled upon some very nice and handy functions which are built in. This post lists some of them and describes in a short what they are used for.

Hey! This article references a pre-release version of Ember.js. Now that Ember.js has reached a 1.0 API the code samples below are no longer correct and the expressed opinions may no longer be accurate.

Ember

The following functions are defined in packages/ember-runtime/lib/core.js and packages/ember-metal/lib/utils.js respectively.

If you need a given object to be an array you can use this function. If the passed object is already an array it simply returns it, otherwise it creates an array of length 1, where the passed object is the only item.

This function compares two objects of possibly different types. It returns -1 if the first argument is smaller, 0 if both are equal and 1 if the first is greater than the second. The comparison order of different types is defined in Ember.ORDER_DEFINITIONS.

Checks if the passed two arguments are logically equal. If the first passed object has a isEqual, this function is used. The contents of two arrays are not compared. As stated in the corresponding test, this would be too expensive.

Ember.K simply is a function returning this. This might sound not very useful but I use it often during developing a view using the action helper. Because an error is thrown when a specified target cannot handle the triggered action I simply create a property and assign it to Ember.K and continue writing the view. You can even use the shorter alias Em.K.

Tom Dale talked about this at the Ember.js Meetup, held on 21. February 2012. I encourage you to watch this video if you haven’t already seen it. And watch it again if you already have. It’s about debugging Ember.js apps and it’s shipped with very nice humor, bro.

String

The functions described below are directly available on String’s unless Ember.EXTEND_PROTOTYPES is set to false as described here.

This method formats the passed string but first checks if its a key in the Ember.STRINGS hash. By doing so it is possible to have a central point for defining the strings used in an application. This also allows internationalization. As stated in the source code its recommended - though not required - to prefix such a string with an underscore so it can be easily distinguished from ‘normal’ strings.