Last active
September 29, 2017 07:03
-
-
Save zzbo/3b2cc908e405488d2b58ecb88a731b19 to your computer and use it in GitHub Desktop.
EventEmitter
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
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