Open In App

Ember.js Application initializer() Method

Last Updated : 10 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Ember.js is a JavaScript web framework that utilizes a component-service pattern. It is Open-Sourced. The Ember Js Applications when booted up can use initializers to set up the environment and its functionality by the user.

Syntax:

ember generate initializer <initializer-name>

Attributes: The Initializer object has four attributes that are used to define its execution process:

  1. name: this is used to define the name of the initializer. This must be unique.
  2. before: this is used to ensure that the current initializer is run before the given initializer
  3. after: this is used to ensure that the current initializer is run after the given initializer
  4. initialize: this is used to call the initialize() function of the initializer object.

Method: 

  • initialize(): It is the function where the code which is to run during this initializer process is specified.

Create An Ember App: Now we need to create an Ember app. Go to the directory where you want to save the application and run the command:

ember create my-app

Create Ember Application

Example 1: We will create an initializer ‘first’ which will be the first one to be called after the application starts.

Run the command:

ember generate initializer first

Add the following code in the first.js file created by the command in the initializer command.

Javascript




import { debug } from '@ember/debug';
  
export function initialize() {
  debug('This is The First initializer!');
}
  
export default {
  name: 'first',
  initialize
};


Output:

This is The First initializer!

Example 2: If we want we can just use one initializer but in some situations, we might need more than one initializers. Then we need to define which initializer is executed in which order. Now to use the functionality of ‘before’ and ‘after’ we will create two more initializers ‘start’ and ‘second’.

Run the commands:

ember generate initializer second
ember generate initializer start

Now paste the following code into the second.js.

Javascript




import { debug } from '@ember/debug';
  
export function initialize() {
  debug('This is The Second initializer!');
}
  
export default {
  name: 'second',
  after: 'first',
  initialize
};


Now paste the following code in start.js:

Javascript




import { debug } from '@ember/debug';
  
export function initialize() {
  debug('This is The Starting initializer!');
}
  
export default {
  name: 'start',
  before: 'first',
  initialize
};


As we used the before attribute in start.js it is executed before first.js and second.js is executed after first.js because we used the after the keyword.

Run the command:

ember server

Output: Go To localhost:4200 and open the console to see the desired behavior.

Initializers Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads