在自定义Handlebars帮助程序中访问全局应用程序状态

时间:2014-04-25 18:10:42

标签: ember.js handlebars.js

在ember.js应用程序中,我正在寻找一种优雅的方法来从自定义手柄助手中访问全局应用程序状态(例如配置/会话数据,有关登录用户的信息等)。使用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帮助器注册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);
});

2 个答案:

答案 0 :(得分:1)

帮助程序是孤立的(如组件),您需要传入所需的任何外部依赖项才能使用它们。

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);
});

答案 1 :(得分:0)

如果您使用带有不同功能参数的 Ember.Handlebars.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);

    });

请注意,使用此方法创建的帮助程序在数据更改时不会重新呈现其内容。如果您需要定义一个"绑定帮助器",请查看Ember Handlebars Helpers

相关问题