Skip to content

Instantly share code, notes, and snippets.

@zzbo
Last active September 29, 2017 07:03
Show Gist options
  • Save zzbo/3b2cc908e405488d2b58ecb88a731b19 to your computer and use it in GitHub Desktop.
Save zzbo/3b2cc908e405488d2b58ecb88a731b19 to your computer and use it in GitHub Desktop.
EventEmitter
let isFunction = function (obj) {
return typeof obj === 'function' || false;
};
class EventEmitter {
constructor() {
this.listeners = new Map();
}
on(label, callback) {
this.listeners.has(label) || this.listeners.set(label, []);
this.listeners.get(label).push(callback);
return this;
}
off(label, callback) {
let listeners = this.listeners.get(label);
let index;
if (listeners && listeners.length) {
index = listeners.reduce((i, listener, index) => {
return (isFunction(listener) && listener === callback) ?
i = index :
i;
}, -1);
if (index > -1) {
listeners.splice(index, 1);
this.listeners.set(label, listeners);
return true;
}
}
return false;
}
emit(label, ...args) {
let listeners = this.listeners.get(label);
if (listeners && listeners.length) {
listeners.forEach((listener) => {
listener(...args);
});
return true;
}
return false;
}
}
export default EventEmitter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment