EmberJS - Object Model Dynamic Updating



Computed properties detect the changes made on the properties and dynamically update the computed property when they are called by using the set() method.

Syntax

ClassName.set('VariableName', 'UpdatedValue');

Example

The following example shows dynamically updated value when changes are made to the properties −

import Ember from 'ember';

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

      Details2: Ember.computed('age', 'mobno', function() {
         return 'Name: ' + this.get('Details1') + '<br>' + ' Age: ' + this.get('age') + 
            '<br>' + ' Mob No: ' + this.get('mobno');
      }),
   });

   //initializing the Person details
   var person_details = Person.create ({
      //Dynamically Updating the properties
      firstName: 'Jhon',
      lastName: 'Smith',
      age: 26,
      mobno: '1234512345'
   });

   //updating the value for 'firstName' using set() method
   person_details.set('firstName', 'Steve');
   document.write("<h2>Details of the Person: <br></h2>");
   document.write(person_details.get('Details2'));
}

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

import dynamicupdating from './dynamicupdating';

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

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

dynamicupdating();

Output

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

Ember.js Dynamic Updating
emberjs_object_model.htm
Advertisements