-
-
Save w3guy/f3e7a626b6745f666e2da5ddde785a81 to your computer and use it in GitHub Desktop.
JavaScript Event Emitter
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
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