Skip to content

Instantly share code, notes, and snippets.

@maxkostinevich
Created February 16, 2016 10:04
Show Gist options
  • Save maxkostinevich/11f07b125e270816b4c1 to your computer and use it in GitHub Desktop.
Save maxkostinevich/11f07b125e270816b4c1 to your computer and use it in GitHub Desktop.
JavaScript Event Emitter
function Emitter() {
this.events = {};
}
Emitter.prototype.on = function (type, listener) {
this.events[type] = this.events[type] || [];
this.events[type].push(listener);
}
Emitter.prototype.emit = function (type) {
if(this.events[type]){
this.events[type].forEach(function(listener){
listener();
});
}
}
// Usage
var emtr = new Emitter();
emtr.on('myevent', function(){
console.log('Function 1');
});
emtr.on('myevent', function(){
console.log('Function 2!');
});
emtr.emit('myevent');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment