簡體   English   中英

在自定義Handlebars幫助器中訪問全局應用程序狀態

[英]Accessing global application state inside a custom Handlebars helper

在ember.js應用程序中,我正在尋找一種從自定義手把助手中訪問全局應用程序狀態(例如,配置/會話數據,有關已登錄用戶的信息等)的優雅方法。 使用Ember.Application.initializer在路由/控制器中很容易做到這一點, 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);
});

助手是孤立的(像組件一樣),您需要傳入任何需要使用的外部依賴項。

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.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM