Ember.js Set up constants

Quang Nguyen
quangtn0018
Published in
2 min readSep 3, 2018

What if you needed one place where you can access all of your constants in Ember? We want to write clear and concise code, and if we have a large project where each file contains 1000+ lines of code, we would want to separate the constants in another file right? It is good practice to modularize code anyway.

One thing you can do is declare constants as global variables. That’s not bad but it’s not considered the best practice because we might not use them in all our components, routes, or controllers, and having them live throughout the entire program could take up precious memory. We would want to look for a solution where it is efficient and convenient to inject these constants in places where we need to access them.

That’s where service injections using initializers comes in. More info on injecting services using initializers can be found here on the ember guide.

The gist of it is, you can create a service and an initializer using the Ember CLI command in the terminal at the root of your Ember application:

ember g service constantsember g initializer constants

You can replace constants with your service and initializer name. Then in your service, you can create your constants:

// services/constants.jsimport Ember from ‘ember’;export default Ember.Service.extend({
chickens: 0,
eggs: 0
});
// initializers/constants.jsexport function initialize(application) {
application.inject(‘route’, constants, ‘service:constants’);
};
export default {
name: ‘constants’,
initialize: initialize
};

The second parameter in the inject method above is the name of the property that you will access from in your routes, like this:

// routes/access-constants.jsimport Ember from ‘ember’;export default Ember.Route.extend({
setupController(controller, model) {
// Call _super for default behavior
this._super(controller, model);
// Implement your custom setup after
this.controller.set(“chickensCount”, “constants.chickens”);
this.controller.set(“EggsCount”, “constants.eggs”);
}
});

More info on setupController for those of you who are curious.

If you want to know the other ways of declaring and using constants, look at this ember discussion post.

I really like this way of injecting services into all routes (you can inject them into components and controllers too) because it’s more convenient and you don’t have to individually inject these services in each places where you need them. They’ll be injected from the initializer and that’s a plus for modularity and concise code.

--

--