Jeremie Ges
Jeremie Ges

Reputation: 2745

How to set a global variable in an ember JS application

Before my Ember application boots, I would like to dynamically set a variable depending the URL:

// Dummy example
if (window.location.hostname == 'awesomewebsite.com') {
  // Set a "global variable" called town
}

I want to have the possibility to rely on that variable to do some stuff afterwards (in a component, template and so on).

What will be the best way to do that ?

Upvotes: 4

Views: 6869

Answers (1)

EnricoB
EnricoB

Reputation: 151

You can use an initializer to add a variable to the window or the ember environment object.

https://guides.emberjs.com/v2.5.0/applications/initializers/

Initializer for window object:

export function initialize() {
  if (window.location.hostname == 'awesomewebsite.com') {
    // Set a "global variable" called town
    window.myApp.town= 'foo.bar';
  }
};

export default {
  name: 'init-environment',
  initialize: initialize
};

Initializer for ember environment object: (https://guides.emberjs.com/v2.5.0/configuring-ember/configuring-your-app/)

import ENV from 'your-application-name/config/environment';

export function initialize() {
  if (window.location.hostname == 'awesomewebsite.com') {
    // Set a "global variable" called town
    ENV.App.town = 'foo.bar';
  }
};

export default {
  name: 'init-environment',
  initialize: initialize
};

Upvotes: 6

Related Questions