Skip to content

Instantly share code, notes, and snippets.

@joaomilho
Last active Dec 6, 2020
Embed
What would you like to do?
Type safe event handlers
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