Created
March 13, 2018 18:29
-
-
Save prozacgod/d9748e62dfa9b5d68ca8b39c7226cea8 to your computer and use it in GitHub Desktop.
Simple EventEmitter for TS
This file contains hidden or 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
interface EventEmitterHandlers { | |
[s: string]: IAction1<any>[]; | |
} | |
class EventEmitter { | |
private events: EventEmitterHandlers = {}; | |
on(event: string, listener: IAction1<any>) { | |
!(event in this.events) && this.events[event] = []; | |
this.events[event].push(listener); | |
} | |
once(event: string, listener: IAction1<any>) { | |
this.on(event, function _handler (data) { | |
this.removeListener(event, _handler); | |
listener(data); | |
}); | |
} | |
removeListener(event: string, listener?: IAction1<any>) { | |
let idx; | |
if (event in this.events) { | |
if (listener) { | |
idx = this.events[event].indexOf(listener); | |
if (idx > -1) { | |
this.events[event].splice(idx, 1); | |
} | |
} else { | |
this.events[event] = []; | |
} | |
} | |
} | |
emit(event: string, data: any) { | |
this.events[event] && this.events[event].forEach((listener) => listener(data)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment