如何在ember JS应用程序中设置全局变量

Jer*_*Ges 4 ember.js

在我的Ember应用程序启动之前,我想根据URL动态设置变量:

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

我希望有可能依赖该变量来做一些事情(在组件,模板等中).

最好的方法是什么?

小智 5

您可以使用初始化程序将变量添加到窗口或ember环境对象.

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

窗口对象的初始化程序:

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
};
Run Code Online (Sandbox Code Playgroud)

ember环境对象的初始化程序:(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
};
Run Code Online (Sandbox Code Playgroud)