Created
January 12, 2016 16:04
-
-
Save olanod/56b01674e2a02379a514 to your computer and use it in GitHub Desktop.
Super simple and elegant implementation of an event emitter that follows the EventTarget interface of browsers using ES6 goodness.
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
// store for private variables | |
let _ = new WeakMap(); | |
/** | |
* Event emitter following browser's EventTarget interface | |
*/ | |
export class EventEmitter { | |
constructor() { | |
_.set(this, { callbacks: new Map() }); | |
} | |
addEventListener(type, listener) { | |
let callbacks = _.get(this).callbacks; | |
if (!callbacks.has(type)) | |
callbacks.set(type, new Set()); | |
if (typeof listener == 'function') | |
callbacks.get(type).add(listener); | |
} | |
dispatchEvent(type, ...args) { | |
let listeners = _.get(this).callbacks.get(type); | |
if (listeners) { | |
for (let listener of listeners) { | |
listener.apply(this, args); | |
} | |
} | |
} | |
removeEventListener(type, listener) { | |
let listeners = _.get(this).callbacks.get(type); | |
if (listeners) | |
listeners.delete(listener); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment