redconservatory
redconservatory

Reputation: 21934

Ember cli, how to initialize a service with a controller?

I have a service, called clock

//app/services/clock.js

export default Ember.Object.extend({
    pulse: Ember.computed.oneWay('_seconds').readOnly(),
    tick: function () {
      var clock = this;
      Ember.run.later(function () {
        var seconds = clock.get('_seconds');
        if (typeof seconds === 'number') {
          clock.set('_seconds', seconds + (1/4));
        }
      }, 250);
    }.observes('_seconds').on('init'),
    _seconds: 0
});

I also have an initialzer where I want to register the clock service and then inject it into my "interval" route/controller.

// app/initializers/clock-service.js

import ClockService from 'app/services/clock'; 

export default {
        name: 'ClockServiceInitializer', 
        initialize: function(container, application) {
          container.register('clock:service', ClockService);
          app.inject('controller:interval', 'clock', 'clock:service');
  }
}; 

Edit: it appears to be this:

export default {
  name: 'services',
  initialize: function(container, app) {
    // Inject into all routes and controllers

    // Or if you wanted, into a specific route
    app.inject('controller:index', 'clock', 'service:clock');
  }
};

Upvotes: 0

Views: 2208

Answers (1)

Jon
Jon

Reputation: 1234

I have basically the same thing, though I inject into all controllers.

In the initializer:

//container.typeInjection('component', 'store', 'store:main');
application.register('clock:service', ClockService, { singleton: true });
application.inject('controller', 'clock', 'clock:service');

And in the controller, using it like:

updateView: {
  // ...
}.observes('clock.pulse')

Upvotes: 2

Related Questions