How to dependency inject into handlebars helpers


#1

I want to build some kind of a simple translation mechanism, i.e. keys should be replaced with values in templates. I looked into ember-i18n and saw that it registers its translation data in the Ember namespace in an initializer, which can then be accessed from within a helper.

I actually don’t want to mess around with any vendor object, so I tried to inject in the initializer like

app.register("data:main", data, {instantiate: false, singleton: true})
app.inject("helper", "data", "data:main")

But there is no data object in the helper available. In fact this refers to the current context where the helper was called and not to any specific object.

So how would I inject dependencies into a helper? Or what would be a “clean” solution to this problem?


#2

I came across the same problem. In my case, the injected property worked in one case but gave undefined in the other case. (so in your case, this.data would be the data:main instance in one case and undefined in the other case)

The imperfect solution I ended up with is to look up the data instance from the container:

var data = this.container.lookup('data:main');

I know, this gets around the inject part of the register-inject pair and thus is directly coupled to the registered name which is hacky but at least it works.