Created
November 28, 2014 10:05
-
-
Save chrism/324a5d82679147f35ba5 to your computer and use it in GitHub Desktop.
Dependency Injection in Ember using Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Ember from 'ember'; | |
export default Ember.Route.extend({ | |
setupController: function() { | |
this.poller.start(); | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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