Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting function with initializer in ember-cli

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?

like image 411
Duncan Walker Avatar asked Dec 19 '22 13:12

Duncan Walker


1 Answers

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

like image 98
Kingpin2k Avatar answered Dec 27 '22 00:12

Kingpin2k