EmberJS - Classes and Instances



This is nothing but updating the class implementation without redefining it and reopening the class by specifying new properties in it. This is possible by using the following methods −

  • reopen() − It adds properties and methods to instances.

  • reopenClass() − It adds properties and methods to the classes..

Example

The following example uses the methods mentioned above and specifies the new properties or methods in it −

import Ember from 'ember';

export default function() {
   //reopen() method for instances
   var Person = Ember.Object.extend ({
      firstName: null,
      lastName:  null,
   });

   //adding new variable to the Person class
   Person.reopen ({
      middleName: 'Smith',
   });

   document.write('Middle Name: '+Person.create().get('middleName'));
   document.write("<br>");

   //reopenClass() method for classes
   Person.reopenClass ({
      //creating new function for class Person
      openClass: function() {
         return Person.create({isMan: true});
      }
   });

   document.write('isMan: '+Person.openClass().get('isMan'));
}

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

import reopenclass from './reopenclass';

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

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

reopenclass();

Output

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

Ember.js Reopenclass Instance
emberjs_object_model.htm
Advertisements