Skip to content

Instantly share code, notes, and snippets.

@chrism
Created November 28, 2014 10:05
Show Gist options
  • Save chrism/324a5d82679147f35ba5 to your computer and use it in GitHub Desktop.
Save chrism/324a5d82679147f35ba5 to your computer and use it in GitHub Desktop.
Dependency Injection in Ember using Singleton
import Poller from '../utils/poller';
export function initialize(container, application) {
var poller = Poller.create();
// this works but I want a singleton
// application.register('poller:main', poller, { instantiate: false });
application.register('poller:main', poller);
application.inject('route', 'poller', 'poller:main');
application.inject('controller', 'poller', 'poller:main');
}
export default {
name: 'poller',
initialize: initialize
};
import Ember from 'ember';
export default Ember.Route.extend({
setupController: function() {
this.poller.start();
}
});
import Ember from 'ember';
export default Ember.Object.extend({
interval: function() {
return 5000; // Time between polls (in ms)
}.property().readOnly(),
// Schedules the function `f` to be executed every `interval` time.
schedule: function(f) {
return Ember.run.later(this, function() {
f.apply(this);
this.set('timer', this.schedule(f));
}, this.get('interval'));
},
// Stops the pollster
stop: function() {
Ember.run.cancel(this.get('timer'));
},
// Starts the pollster, i.e. executes the `onPoll` function every interval.
start: function() {
this.set('timer', this.schedule(this.get('onPoll')));
},
onPoll: function() {
Ember.Logger.log('basic poller overwrite with your method');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment