Working with application initializers

Application initializers can be used to configure your application as it boots. It's the primary place to set up dependency injections in your application.

In this example, we'll examine when an application initializer is run.

How to do it...

  1. In a new application, create initializer:
    $ ember g initializer application
    

    This will create a new application initializer. This will be run as soon as the application boots.

  2. Add an alert box to the initializer:
    // app/initializers/application.js
    export function initialize( application ) {
        alert('loading application');
    }
    
    export default {
        name: 'application',
        initialize
    };

    This will load an alert box as soon as the application loads.

  3. Run ember server and you should see an alert box displayed before the application is loaded:
    How to do it...

    Nothing else has loaded in the application before this alert box is shown.

  4. If needed, we can also register or inject services in the initializer. It may look as follows:
    // app/initializer/application.js
    export function initialize(app) {
        app.inject('component', 'start', 'service:start');
    }
    
    export default {
        name: 'init',
        initialize
    };

    This takes the service named start and injects it into all the components. You can see more examples of this in Chapter 9, Real-Life Tasks with Ember.js.

    Tip

    Application instance initializers

    Application instance initializers run when the instance is loaded. It was added with Ember's FastBoot to make it easier to run many requests concurrently. During bootup, application initializers are run first, then instance initializers. If needed, you can look up factories you've already registered in the application initializer in the instance initializer.

    For the most part, you'll only be using instance initializers for certain A/B testing configurations, configuring initial states, and when working with the Ember FastBoot server. To generate an instance initializer, run ember g instance-initializer <name>.

How it works...

Application initializers are run as soon as the application boots. This is the primary place to configure dependency injections into your application. Try to keep initializers as lightweight as possible. More complexity added to an initializer might cause delay in the application loading. Things like asynchronous loading conditions will work better in a service or route hook instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset