Skip to content

Instantly share code, notes, and snippets.

@olanod
Created January 12, 2016 16:04
Show Gist options
  • Save olanod/56b01674e2a02379a514 to your computer and use it in GitHub Desktop.
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.
// 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