Observers in Ember.js

Observers in Ember.js are methods that observe one or more object properties and are called when these properties change.

At first, they may seem similar to computed properties, but in reality they are completely different from them. One very big difference being that computed properties are functions which behave like normal properties that can be accessed via, get and set methods, and can be used in templates like any other property.

Observers on other hand are like listeners in JavaScript. They observe properties, and get called when these properties changes. They cannot be accessed like properties neither can they be used in templates. Let us see an example of observer chapter-2/example8:

import Ember from 'ember';

export default Ember.Object.extend({
  time:00,
  timeChanged: function(){
    //Do something when time changes
    console.log('time changed'),
  }.observes('time')
});

The contents of time_manager.js are present in chapter-2/example8/app/time_manager.js

import timeManager from './time_manager';

var myTimeManager = timeManager.create({
  time: 12
});

myTimeManager.set("time",22);

//Output
//time changed

Time manager being used in app.js is present in chapter2/example8/app/app.js

Here, we have created a time manager, which has a property called as time. We have created an observer, timeChanged, which monitors the time property. Whenever the time property changes, the observer is fired. myTimeManager is an instance of timeManager. Let's change the time of myTimeManager and see if the observer is fired or not. If you run the above code, you will see that time changed is printed on the console.

As timeChanged is an observer and not a property, if you try and get the property timeChanged on the object, you will get the function instead of the property. You can also manually invoke the observer by using myTimeManager.timeChanged(), just like any other method.

Note

One important thing to note here is that observers are fired only after the object is fully initialized. If we want an observer to fire during the object initialization, we can instruct the framework to do that too.

In the above code, the observer is fired only after you change the time property, using the set method. If we want the observer to be called even when the object was initializing, we can do that by using observes('time').on('init'). Doing this will trigger the observer twice; once during the object creation and initialization, and second time when we change the value of time property by using set.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.202.27