EmberJS - Classes and Instances



Class is a template or blue print, that has a collection of variables and functions, where as instances are related to the object of that class. Creating and extending the Ember class on Ember.Object is the main property of the Ember object model.

Defining Classes

You can create new Ember class by using the Ember.Object's extend() method −

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

The above code creates new Ember class called "Demo" which inherits the properties from initializers, computed properties, etc. After creating the class, you need to create instance of it by using the create() method as shown below −

const state = Demo.create();

Using the above instance "state", access the properties by using the set and get accessor methods.

console.log(state.get('stateOn'));

You can change the "stateon" property by using the set method as shown below −

state.set('stateOn', true);

Initializing Instance

You can initialize the new instance by invoking the init() method. When declaring objects in the class, you need to initialize each instance with the init() method.

Example

The following example uses the above mentioned properties and displays an alert message when an Ember object is initialized −

import Ember from 'ember';   //import ember module
export default function() {
   
   //new ember object
   const Demo = Ember.Object.extend ({
      init() {
         alert('The default property of stateOn is : ' + this.get('stateOn'));
      },
      stateOn: false
   });

   const state = Demo.create();   //new instance from object with create() method
   state.set('stateOn', true);
   console.log(state.get('stateOn'));
}

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

import classinstance from './classinstance';

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

classinstance();

Output

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

Ember.js Class Instance
emberjs_object_model.htm
Advertisements