I have an app built on Ember-cli. I am trying to inject a method into all routes, controllers, and views. I am aware I could utilize the app/utils
directory and import the method's module into all the files that call it, but I would like the method to be automatically available. Hence, I have chosen to inject the method using an initializer.
The initializer looks like this:
export default {
name: 'injectMethod',
initialize: function(container, app) {
var someFunction = function(message) {
};
app.register('function:main', someFunction);
Em.A(['route', 'controller', 'view']).forEach(function(place) {
app.inject(place, 'someFunction', 'function:main');
});
}
};
This results in the following error message: Uncaught TypeError: undefined is not a function
. The error disappears when I remove the app.inject()
line.
Are initializers handled differently in ember-cli and/or is something in the above code incorrect? Or is they a better way to achieve my goal than using an initializer?
Ember expects you to register a factory which it can create instances using the create
method. If you are passing in an instance (or just a method) you would need to tell Ember not to attempt to instantiate it and just use the instance passed in.
export default {
name: 'injectMethod',
initialize: function(container, app) {
var someFunction = function(message) {
};
app.register('function:main', someFunction, {instantiate: false});
Em.A(['route', 'controller', 'view']).forEach(function(place) {
app.inject(place, 'someFunction', 'function:main');
});
}
};
Example: http://emberjs.jsbin.com/xaboliwu/1/edit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With