Accessing the Global App Object in an Ember CLI App

While upgrading my good ol’ Ember app to Ember CLI, one of my components was complaining it couldn’t find App.

There were a handful of calls like App.__container__.lookup('controller:team'); scattered throughout the codebase.

Recent versions of Ember CLI removed the global App object. How do we get it back?

Create an instance initializer by running mkdir app/instance-initializers && touch app/instance-initializers/global.js (there is no ember generate instance-initializer yet!). Then type this:

// app/instance-initializers/global.js

export function initialize(application) {
  window.App = application;  // or window.Whatever
}

export default {
  name: 'global',
  initialize: initialize
};

You will now have the window.App global.

Bonus: Get access to the Ember Data store from the App object

This is one extra line of code away (highlighted). Using Ember’s container we attach the store to the application. Our file would look like this instead:

// app/instance-initializers/global.js

export function initialize(application) {
  application.store = application.__container__.lookup('service:store');
  window.App = application;  // or window.Whatever
}

export default {
  name: 'global',
  initialize: initialize
};

Now App.store is readily available in the console. Very handy.

Enjoyed this article? Don't miss my next one!

Leave me your e-mail for content that will help you master Ember:

Do you want to master Ember fast?

Leave me your e-mail for helpful updates delivered straight to your inbox.

(A few e-mails per month. No BS. Unsubscribe anytime!)