Where would I put a global constants file?


#1

I am using ember-cli to build my EmberJS application. I want to create a global constants file, and I have 2 questions.

  1. Where would I put this file? I’m thinking maybe under “models” but I’m not too sure about it.
  2. How would I implement it. Would I just extend it from Ember.Object?

Thanks.


#2

The boring simple way would be something like this:

// file: app/constants.js
export default {
  Constant1: 'bob',
  Constant2: 'cupcakes'
}

// file: app/models/example.js
import Constants from '<app-name-here>/constants';

// shorthand for const Constant1 = Constants.Constant1
const { Constant1, Constant2 } = Constants;

#3

I’d recommend using the config/environment.js file for any constants/config settings. You can add arbitrary properties and access them from any of your files by importing the file.

See http://www.ember-cli.com/user-guide/#Environments for more details on how it’d work.


#4

I created a service like this:

// app/services/constants.js
export default Ember.Service.extend({
    firstConstant: 'test',
    anotherOne: 25
});

and an associated initializer (same file name) that injects the service in to all routes like this:

// app/initializers/constants.js
export function initialize(registry, application) {
    application.inject('route', 'constants', 'service:constants');
    application.inject('controller', 'constants', 'service:constants');
}
export default {
    name: 'constants',
    initialize: initialize
};

The service is a singleton & can be accessed in your routes & controllers like this:

this.get('constants')

For more details take a look at this article:

http://www.hutchinson.io/ember-services-and-dependency-injection/


#5

I don’t know how “Ember-y” this is, but, plain and simple, you can still use javascript globals (window is the global object, so globals are actually properties on the window object, but I digress)

window.SOME_CONSTANT = 'localhost'

Exactly where you put this code? Perhaps right in config/environment.js as dnegstad suggested, or, config/constants.js and then do import 'constants' in environment.js I am guessing that import style works, you might need to follow the ‘happy path’ and do import module from ‘file’


#6

That’s all ok until you need to translate your constants. And you’ll do that:

// file: app/constants.js

let Consts = Ember.Object.extend({

  i18n: Ember.inject.service(),

  REQUEST_STATE: Ember.computed('i18n.locale', function(){
    var i18n = this.get('i18n');
    return {
      new: i18n.t("consts.requestState.new"),
      pending: i18n.t("consts.requestState.pending"),
      canceled: i18n.t("consts.requestState.canceled")
    }
  })

}); 

export default Consts.create();