0
votes

I wanted to understand if the needs attribute could be used to inject arbitrary objects into controllers, routes and views.

I am developing an Ember.js application where I am writing a custom data-service layer that communicates with the backend to load and persist data. I define Ember Objects which represent the various backend services such as:

App.SessionServiceClient = Em.Object.extend({
  // methods and attributes
});

App.UserServiceClient = Em.Object.extend({
  // methods and attributes
});

I now register these objects with the application's container to make them available for DI:

App.register('service:session', App.SessionServiceClient, {singleton: false});
App.register('service:user', App.UserServiceClient, {singleton: false});

Now that the objects are available for injection, and if I have a controller that needs only the SessionServiceClient, can I do the following:

App.SignInController = Em.ObjectController.extend({
  needs: ['service:user'],                  // using the needs to declare dependency
  actions: {
    // actions for the view
  }
});

When i tried this, it did not work. Is this possible with Ember.js or am I doing it wrong?

1

1 Answers

1
votes

Best practice is to use initializers to inject your service into the controllers you need it in. SEe http://ember.zone/ember-application-initializers/

Ember.Application.initializer({
 name: "sessionLoader",
 after: "store",

 initialize: function(container, application) {
    container.register('service:session', App.SessionServiceClient, {singleton: false});
    container.injection('route', 'session', 'service:session');
    container.injection('controller', 'session', 'service:session');
  });
}
});

Also you should really try to switch to Ember-CLI or at least use an ES6 module structure. (i.e. use imports instead of globals.)