Last active
December 17, 2018 21:51
-
-
Save daliborgogic/c848bd0871be19146987d4a4bcf949c4 to your computer and use it in GitHub Desktop.
JavaScript EventEmitter (for node.js and browsers)
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
class EventEmitter { | |
constructor() { this.events = {} } | |
getEventListByName(eventName){ | |
if(typeof this.events[eventName] === 'undefined'){ | |
this.events[eventName] = new Set() | |
} | |
return this.events[eventName] | |
} | |
on(eventName, fn) { this.getEventListByName(eventName).add(fn)} | |
once(eventName, fn) { | |
const self = this | |
const onceFn = function(...args){ | |
self.removeListener(eventName, onceFn) | |
fn.apply(self, args) | |
} | |
this.on(eventName, onceFn) | |
} | |
emit(eventName, ...args) { | |
this.getEventListByName(eventName).forEach(function (fn) { | |
fn.apply(this,args) | |
}.bind(this)) | |
} | |
removeListener(eventName, fn) { this.getEventListByName(eventName).delete(fn) } | |
} | |
const emitter = new EventEmitter() | |
// node.js | |
module.exports = emitter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment