By Oleksii Rudenko December 14, 2014 1:34 PM
Ember.js: My Observers Do Not Work or RTFM

Dear readers,

sometimes my code does not work as expected although every line of it looks completely correct. Two possible causes of this exist: either there is a problem with the software my code relies on or I didn’t read the docs carefully enough to see what is wrong with my code. I have to say that the former happens rarely and the latter is almost always the case.

Observers in Ember.js may easily confuse you if you use them together with the init method. After I learned how to use observers I tended to think that they are firing whenever a property they listen to changes. But this is not true if a property is changed during the object initialization.

Ember Starter Kit

The property1 gets the value ‘value1’ during the initialization. And there is an observer that updates property2 with the value of the property1 whenever the latter changes. When the button is clicked the value of the property2 is alerted.

You would expect that the alerted value equals ‘value1’ but the actual result is undefined because the observer method is never called.

One must explicitly specify that the observer should run on initialization using the following construct:


property1Observer: function () {
    this.set('property2', this.get('property1'));
}.observes('property1').on('init'),

Now it works as expected :-)

Please comment and share whether you knew this or I am the only one who missed the paragraph explaining this feature.