-
-
Save ademilter/df990a8480773e46ee8483e8bd1c98da 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
type EventHandler<T=any> = (data :T)=>void | |
export class EventEmitter<EventMap = {[k:string]:any}> { | |
_events = new Map<keyof EventMap,Set<EventHandler>>() | |
addListener<K extends keyof EventMap>(e :K, handler :EventHandler<EventMap[K]>) { | |
let s = this._events.get(e) | |
if (s) { | |
s.add(handler) | |
} else { | |
this._events.set(e, new Set<EventHandler>([handler])) | |
} | |
} | |
on<K extends keyof EventMap>(e :K, handler :EventHandler<EventMap[K]>) { | |
return this.addListener(e, handler) | |
} | |
removeListener<K extends keyof EventMap>(e :K, handler :EventHandler<EventMap[K]>) { | |
let s = this._events.get(e) | |
if (s) { | |
s.delete(handler) | |
if (s.size == 0) { | |
this._events.delete(e) | |
} | |
} | |
} | |
triggerEvent<K extends keyof EventMap>(e :K, data? :EventMap[K]) { | |
let s = this._events.get(e) | |
if (s) for (let handler of s) { | |
handler(data) | |
} | |
} | |
} |
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
interface FooEvents { | |
"open": undefined | |
"close": Error|undefined | |
} | |
class Foo extends EventEmitter<FooEvents> { | |
open() { | |
this.emitEvent("open") | |
} | |
close(reason? :Error) { | |
this.emitEvent("close", reason) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment