Last active
February 5, 2020 12:12
-
-
Save mizchi/c7363b9648ea3e5637bd017cd86b09c8 to your computer and use it in GitHub Desktop.
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
class EventEmitter { | |
_handlersMap = new Map<string, Function[]>(); | |
on(event: string, fn: Function) { | |
if (this._handlersMap.has(event)) this._handlersMap.set(event, []); | |
const funcs = this._handlersMap.get(event); | |
funcs.push(fn); | |
} | |
emit(event: string, ...args: any) { | |
const funcs = this._handlersMap.get(event); | |
if (funcs && funcs instanceof Array) { | |
for (const fn of funcs) { | |
fn(...args); | |
} | |
} | |
} | |
removeEventListener(event: string, fn: Function) { | |
let funcs = this._handlersMap.get(event) || []; | |
const n = funcs.indexOf(fn); | |
if (n > -1) funcs.splice(n, 1); | |
if (funcs.length === 0) this._handlersMap.delete(event); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment