How To Use Ember Observers
Ember Observers monitor properties for changes unlike Fringe observers who monitor mankind (I really do miss that show). Ember observers are invoked whenever a change occurs to any of its observed properties.
In this tutorial we'll go over a simple example of how to use observers and how they compare to computed properties.
What about Computed Properties?
Many people confuse observers with computed properties. Computed properties can get and set methods and can be used in templates like any other property. On the other hand observers just monitor properties and can't be used in templates. They do not have the capabilities to be accessed like properties either.
When in doubt use a computed property instead of an observer. As mentioned by the official guides most problems new Ember developers have can be solved with computed properties instead of observers. To learn more about computed properties check out my tutorial I did on them here.
Let's take a look at a simple example.
In the example below we have a Car Ember object that has a isOn and color property. We'll add a new isOnChanged observer that updates anytime isOn or color changes.
For the sake of simplicity when the observer fires all it does is log to the console.
If we add this object to an existing controller or component we can see it in action.
I added a new action called pressed. When that action is pressed it toggles the lambo property isOn. I added in a status computed property that simply returns the status of the lambo. It's either on or off.
The template is very simple. All we do is display the status and add a button.
If all goes well you should see an output like this.
If you press the 'Press me' button you'll see the text change from The lambo is on to The lambo is off. You'll also notice in the console a new message signaling to us that our observer is working correctly.
If you'd like to try for yourself check out this Embber twiddle of it here.
Keep in mind that observers will fire multiple times if more then one of it's properties changes. This can lead to unexpected issues. You may have observers that rely on other properties that haven't been updated yet.
You'll need to wrap your observers around Ember.run.once to help fix this issue. Check out my Ember run loop tutorial for more information.
In this tutorial we looked at observers, computed properties and how synchronous behavior works.
You'll find as you work with observers that you can easily introduce bugs. Keep that in mind and do a lot of testing.
Question leave a comment below!
Image Credit bloggledygook and Fringe