Ember.js observables. So you like to watch!

Ember.js is the bee's knees. It has 2 way data-bindings, computed properties, and templating (built in). But another cool feature of Ember.js is observables. Observable allow one piece of code to watch another piece of code for changes. When the change happens the "watching" code fires and performs it's specified action. Let's take a look at how easy it is to add this behaviour with Ember.js. First the code: since this example is so simple I've combined the HTML and JS portions into one.

You can see that the HTML references a view, in this case a TextField. We then create our Application, and define the TextField view by adding a single additional method: valueDidChange. There's nothing special about this method by itself, but what's chained on to the end is what does the heavy lifting. The .observes() method takes a single argument commadelimited list of arguments, the value/properties you wish to watch. It then waits, just like Chuck Norris, for those value/properties change and then it leaps into action...and fires an alert box.

Bit of a letdown innit? That particular functionality isn't all that useful so let's build one of our own. Something useful, perhaps a text countdown for a textarea field...the kind Twitter uses. This example is also simple so again let's take a look at the code, and see what it does. Update: The following Gist changed based on Peter's comments listed below. Specifically point #3.

We've already looked at .observes() so next we're focusing on what gets passed into our valueDidChange function. Notice that I've added 3 arguments to the valueDidChange function (watcher, property, value). Watcher is a reference to the element which changed doing the watching, property is a string containing the name of the property being watched, and value contains the current value of "property". In the case of a TextArea field value is a string.

Let's a take a quick step back to the Application definition. In past articles we had an empty Application.create() block, but in this instance we're defining a variable called len. We're setting that number to the "maximum" string length we want our textarea to hold. Then, when someone types into it we simply subtract the length of the value from 140. After we get the new value we have to update App.len. Every object in Ember has a get and a set method (sometimes called getters and setters). You call App.set(), tell it what property you're wanting to change, and then provide a new value. Done. In the view for this app, you can see a lone span tag. Inside the span we reference the current value of App.len. When that value changes, so does the contents of the span tag. Ember is magic I tell you!