Last active
May 14, 2022 11:23
-
-
Save sidola/eaf987d8c4c7e8445b61dc07c33a842f to your computer and use it in GitHub Desktop.
Experimental PubSub impl. as a class
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
class PubSub<T> { | |
private handlers: { [key: string]: any[] } = {} | |
public subscribe<E extends keyof T & string>( | |
event: E, | |
callback: (message: T[E]) => void | |
) { | |
const list = this.handlers[event] ?? [] | |
list.push(callback) | |
this.handlers[event] = list | |
return callback | |
} | |
public unsubscribe<E extends keyof T & string>( | |
event: E, | |
callback: (message: T[E]) => void | |
) { | |
let list = this.handlers[event] ?? [] | |
list = list.filter(h => h !== callback) | |
this.handlers[event] = list | |
} | |
public publish<E extends keyof T & string>( | |
event: E, | |
message: T[E] | |
) { | |
this.handlers[event].forEach(h => h(message)) | |
} | |
} | |
type Events = { | |
warn: { errorCode: number, userMessage: string }, | |
error: { shitThatWentWrong: string }, | |
} | |
const pubSub = new PubSub<Events>() | |
const subHandler = pubSub.subscribe("error", (message) => { | |
console.log(message.shitThatWentWrong) | |
}) | |
pubSub.publish("error", { shitThatWentWrong: "boom" }) | |
// Allowed, correct handler type | |
pubSub.unsubscribe('error', subHandler) | |
// Not allowed, incorrect handler type | |
pubSub.unsubscribe('warn', subHandler) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment