Skip to content

Instantly share code, notes, and snippets.

@w3guy
Forked from maxkostinevich/emitter.js
Created May 25, 2017 05:35
Show Gist options
  • Save w3guy/c989f66a1933fa27385931dab242cf8b to your computer and use it in GitHub Desktop.
Save w3guy/c989f66a1933fa27385931dab242cf8b 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