6

I am learning Ember.js and going through some of the guides. I was reading about observers here: http://emberjs.com/guides/object-model/observers/

I wanted to play around with the example so I copied and pasted it into my js file. After adding an alert statement to the observer callback, I was surprised to find it was not invoked.

http://jsbin.com/UWEseSo/2/edit?js,output

I was able to find that if you add:

person.get('fullName');

Before the call to set the firstName, the observer callback will be invoked. If I set the first name again immediately after the callback would again not be invoked.

Can anyone explain what is going on here?

Thank you.

EDIT-------

I've traced through the code a little more and I now I have an idea on why this behavior may be like this. Although the example seems like there is a bug it may just be an optimization. I observed earlier that if I called "get" the observer would work. If I did not call "get" the observer would not work. I believe Ember.js may just being smart about this and intentionally not bothering to invoke the observer if no "get" was called. They may be doing this because if there was no "get" there is no reason to invoke the observer because the application can not possibly be showing out of date information.

Once "get" is called an internal flag is set to ensure the observer will be invoked on the next "set".

1 Answer 1

15

It looks like you got the explanation right for this behaviour all by yourself, and to confirm your assumptions there is indeed a change that was introduced in rc8 for performance reason mainly.

You can read here the full article on that, under UNCONSUMED COMPUTED PROPERTIES DO NOT TRIGGER OBSERVERS

This means basically that if you need to observe a computed property but aren't currently retrieving it, just get it in your init method.

Hope it helps.

3
  • Thank you, I'm happy to have that link to back up my observation.
    – corsen
    Oct 13, 2013 at 20:35
  • 7
    in that "init" case, it is better to set .observers(..).on("init") instead of the "get in the init method". Jul 25, 2014 at 16:12
  • In case someone ends up here like myself, this answer still holds for Ember 2.0
    – spectras
    Aug 29, 2015 at 21:18

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.