Last active
December 6, 2020 00:29
-
-
Save joaomilho/06513f694889f2a249be3445f1018ea7 to your computer and use it in GitHub Desktop.
Type safe event handlers
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 Events = { | |
start: []; | |
progress: [number]; | |
complete: [string, boolean]; | |
}; | |
class Uploader { | |
listeners: { | |
[key in keyof Events]: ((...params: Events[key]) => void)[]; | |
}; | |
constructor() { | |
this.listeners = { | |
start: [], | |
complete: [], | |
progress: [], | |
}; | |
} | |
addEventListener<Type extends keyof Events>( | |
type: Type, | |
listener: (...params: Events[Type]) => void | |
) { | |
this.listeners[type].push(listener); | |
} | |
onStart() { | |
this.listeners.start.forEach((listener) => { | |
listener(); | |
}); | |
} | |
onProgress() { | |
this.listeners.progress.forEach((listener) => { | |
listener(1); | |
}); | |
} | |
onComplete() { | |
this.listeners.complete.forEach((listener) => { | |
listener("ok", true); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment