Pregunta

In an ember.js application, I'm looking for an elegant way to access global application state (e.g. configuration/session data, information about the logged in user, ect) from within a custom handlebars helper. This is easy to do in routes/controllers using Ember.Application.initializer like so:

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

However there doesn't seem to be any equivalent of this in the Handlebars helper registration api, where you can essentially inject an external dependency.

My use case for example, is that the session data holds the user's date format preference, and I have a custom helper, formatDate where I want to be able to pull in their settings to use as the default format, eg:

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);
});
¿Fue útil?

Solución 2

You can if you use Ember.Handlebars.registerHelper which bring different function parameters. Once, you get the container you could look for any registered instance like your session.

I have not tested, but I think something similar to this example must work:

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

    });

Take in consideration that helpers created with this method will not re-render their content when data changes. If you need to define a "bound helper", take a look at Ember Handlebars Helpers.

Otros consejos

Helpers are isolated (like components), You'll need to pass in any external dependencies needed in order to use them.

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);
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top