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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With