Emberjs custom config variables

不羁的心 提交于 2020-01-14 05:44:10

问题


How would one specify a custom config variable for use in the handlebars template?

For example:

// config/settings.json

{
  "title": "Hello World"
}

// config/foo.json
{
  "bar": "baz"
}

// Template

{{ settings.title }}
{{ foo.bar }}

回答1:


You need to use dependency injection to inject you global variables into the controller. This blog post from Balint Erdi explains it well. Here is a working demo. This is basically what you do

  • Create 2 object - settings and foo.

    var settings = Ember.Object.extend({
      title: 'Hello World'
    });
    
    var foo = Ember.Object.extend({
      bar: 'baz'
    });
    
  • Register these 2 objects in the container using an application initializer.

    container.register('globals:settings', settings, { singleton: true });
    container.register('globals:foo', foo, { singleton: true });
    
  • Inject the 2 registered object into all the controllers.

    application.inject('controller', 'settings', 'globals:settings');
    application.inject('controller', 'foo', 'globals:foo');
    

Here's is the complete code for the above 2 steps in an initializer

Ember.Application.initializer({
  name: "globals",

  initialize: function(container, application) {
    container.register('globals:settings', settings, { singleton: true });
    container.register('globals:foo', foo, { singleton: true });

    application.inject('controller', 'settings', 'globals:settings');
    application.inject('controller', 'foo', 'globals:foo');
  }
});

You can then reference the values in your template as

{{settings.title}}


来源:https://stackoverflow.com/questions/23802629/emberjs-custom-config-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!