Created
February 16, 2016 10:04
-
-
Save maxkostinevich/11f07b125e270816b4c1 to your computer and use it in GitHub Desktop.
JavaScript Event Emitter
This file contains 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
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