Monthly Archives: March 2015

Observables in Javascript

Observables in Javascript
Observable pattern allows us to execute code blocks when a change happens. There are different implementations to support observables in different programming languages. In ECMAScript 6, Object.Observe() was introduced for the same purpose. It allows us to write functions which get called when an object’s properties are changed.

Let’s look at the following code block. It declares an object model and adds and assigns two dynamic properties to the object. They are id and name. It also uses Object.Observe() with an anonymous function to use the changes in the model object.

Let’s look at how this gets executed. In Chrome, the changes are passed to the change function. Here we are just writing it to the console.

chrome_observable

So this was Chrome. Apparently, Internet Explorer still doesn’t support this feature. Here we are loading the same page in Internet Explorer 11. See how it throws error.

ie_observable

So what should we do in such cases as we don’t want Internet Explorer users to be deprived of our wonderful web page. Apparently, people have been thinking about it. Here is a library ObserveJS which allows us to do the same thing. It exploits Object.Observe() if the browser supports so, otherwise, it uses some other implementation.

polymer_observeJS