EmberJS - Bindings



The binding is a powerful feature of Ember.js which helps to create a link between two properties and if one of the properties gets changed, the other one is updated automatically. You can also bind the same object or different objects.

Syntax

ClassName1 = Ember.Object.create ({
   //code here
});

ClassName2 = Ember.Object.extend ({
   //code here
});

ClassName3 = ClassName2.create ({
   //code here
});

The syntax describes binding of two properties ClassName1 and ClassName2. If ClassName2 gets updated, it will be reflected in ClassName1.

Example

The following example creates link between two properties and updates one property when another property gets changed −

import Ember from 'ember';

export default function() {
   var CarOne = Ember.Object.create ({
      //primary value
      TotalPrice: 860600
   });

   var Car = Ember.Object.extend ({
      //creates property which is an alias for another property
      TotalPrice: Ember.computed.alias('CarOne.TotalPrice')
   });

   var CarTwo = Car.create ({
      CarOne: CarOne
   });
   document.write('Value of car before updating: ' + CarTwo.get('TotalPrice'));
   
   //sets the car price
   CarTwo.set('TotalPrice', 930000);
   
   //above car price effects the CarOne
   document.write('<br>Value of car after updating: ' + CarOne.get('TotalPrice'));
}

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

import objectmodelbindings from './objectmodelbindings';

Where, objectmodelbindings is a name of the file specified as "objectmodelbindings.js" and created under the "app" folder.

Next call the inherited "objectmodelbindings" at the bottom, before the export. It executes the objectmodelbindings function which is created in the objectmodelbindings.js file −

objectmodelbindings();

Output

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

Ember.js Object Model Bindings

The object model binding propagates changes in one direction by using the one way binding which is explained in this link.

emberjs_object_model.htm
Advertisements