EmberJS - Observers



The observer observes the property such as computed properties and updates the text of the computed property. It fires when the text is updated or changed.

Syntax

funName1: Ember.computed(function() {
   //code here
}),

funName1: Ember.observer(function() {
   //code here
});

var varname = ClassName.create({
   //code here
});

The following table lists down the properties of an observer −

S.No. Property & Description
1 Observers and Asynchrony

Observers in an Ember.js are currently synchronous.

2 Declaring the Observer

Declaring an obsever without the prototype extensions and outside of class definitions.

Example

The following example shows how to update the text of computed property by using observer −

import Ember from 'ember';

export default function() {
   var Person = Ember.Object.extend ({
      Name: null,
      
      //Defining the Details1 and Details2 computed property function
      Details1: Ember.computed('Name', function() {
         
         //get the Name value
         var Name = this.get('Name');
         //return the Name value
         return Name;
      }),

      Details2: Ember.observer('Details1', function() {
         this.set('Name','Steve Waugh');
      })
   });

   //initializing the Person details
   var person = Person.create ({
      //initial value of Name varialble
      Name: 'Mark Waugh'
   });

   //updating the value for 'firstName' using set() method
   document.write('<strong>The updated name : </strong>' +person.get('Details1'));
}

Now open the app.js file and add the following line at the top of the file −

import observers from './observers';

Where, observers is a name of the file specified as "observers.js" and created under the "app" folder. Now, call the inherited "observers" at the bottom, before the export. It executes the observers function which is created in the observers.js file −

observers();

Output

Run the ember server and you will receive the following output −

Ember.js Observers
emberjs_object_model.htm
Advertisements