Skip to content

Instantly share code, notes, and snippets.

@ademilter
Forked from rsms/event.ts
Created January 29, 2020 14:09
Show Gist options
  • Save ademilter/df990a8480773e46ee8483e8bd1c98da to your computer and use it in GitHub Desktop.
Save ademilter/df990a8480773e46ee8483e8bd1c98da to your computer and use it in GitHub Desktop.
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)
}
}
}
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