Ember.js 在自定义Handlebar助手中访问全局应用程序状态

Ember.js 在自定义Handlebar助手中访问全局应用程序状态,ember.js,handlebars.js,Ember.js,Handlebars.js,在一个ember.js应用程序中,我正在寻找一种从自定义Handlebar helper中访问全局应用程序状态(例如配置/会话数据、有关登录用户的信息等)的优雅方法。在路由/控制器中使用Ember.Application.initializer这样做很容易: App.initializer({ name: 'registerSession', initialize: function(container, application) { application.re

在一个ember.js应用程序中,我正在寻找一种从自定义Handlebar helper中访问全局应用程序状态(例如配置/会话数据、有关登录用户的信息等)的优雅方法。在路由/控制器中使用
Ember.Application.initializer
这样做很容易:

App.initializer({
    name: 'registerSession',
    initialize: function(container, application) {
        application.register(
            'app:session', 
            Ember.Object.extend({userId: 1, dateFormat:"MMMM Do, YYYY", /* ... */}), 
            {singleton: true}
        );

        application.inject('controller', 'session', 'app:session');
        application.inject('route', 'session', 'app:session');
    }
});
然而,在Handlebars helper注册api中似乎没有任何与此等效的内容,您可以在其中本质上注入外部依赖项

例如,我的用例是会话数据保存用户的日期格式首选项,我有一个自定义帮助程序,
formatDate
,我希望能够将其设置作为默认格式使用,例如:

Ember.Handlebars.helper('formatDate', function(timestamp) {
    //need to be able to access the global session data here
    //in order to get the user's date format preference
    return moment.unix(timestamp).format(session.dateFormat);
});
助手是独立的(就像组件一样),您需要传入任何需要的外部依赖项才能使用它们

Ember.Handlebars.helper('formatDate', function(timestamp, format) {
    //need to be able to access the global session data here
    //in order to get the user's date format preference
    return moment.unix(timestamp).format(format);
});

如果您使用带有不同功能参数的Ember.handlebar.registerHelper,则可以使用。一旦获得容器,您就可以查找任何已注册的实例,如会话

我还没有测试过,但我认为类似于此示例的东西必须起作用:

import {handlebarsGet} from "ember-handlebars/ext";

registerHelper('formatDate', function(value, options) {

      var container = options.data.keywords.controller.container;
      var session = container.lookup('app:session');

      var propertyValue;
      if ( options.types[0] !== 'STRING' ) {
         var context = (options.contexts && options.contexts.length) ? options.contexts[0] : this;
         propertyValue = handlebarsGet(context, value, options);
      } else {
         propertyValue = value;
      }

      return moment.unix(propertyValue).format(session.dateFormat);

    });

请考虑使用此方法创建的帮助程序在数据更改时不会重新呈现其内容。如果你需要定义一个“绑定帮助器”,请看。

是的,这正是我所担心的,因为这意味着我每次使用帮助器时都需要传递相同的配置数据,
{{formattate timestamp session.dateFormat}
,这在我看来不是很枯燥,但我想在这方面我没有任何其他选择。我把被接受的答案换成了ppcano的答案,因为它似乎有效地解决了我在这种情况下的需求。然而,我确实理解完全孤立的帮手背后的原因和好处。啊,这非常有效!看起来绑定帮助程序可以通过访问相同的参数/选项数据来创建。以这种方式使用容器是一种反模式。像这样使用它,您还可以定义一个全局属性并跳过一起使用容器。