Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created September 14, 2022 10:57
Show Gist options
  • Save semlinker/b63d748636ef27a0d57dc6c4c251f720 to your computer and use it in GitHub Desktop.
Save semlinker/b63d748636ef27a0d57dc6c4c251f720 to your computer and use it in GitHub Desktop.
Publish-subscribe pattern
type EventHandler = (...args: any[]) => any;
class EventEmitter {
private c = new Map<string, EventHandler[]>();
subscribe(topic: string, ...handlers: EventHandler[]) {
let topics = this.c.get(topic);
if (!topics) {
this.c.set(topic, (topics = []));
}
topics.push(...handlers);
}
unsubscribe(topic: string, handler?: EventHandler): boolean {
if (!handler) {
return this.c.delete(topic);
}
const topics = this.c.get(topic);
if (!topics) {
return false;
}
const index = topics.indexOf(handler);
if (index < 0) {
return false;
}
topics.splice(index, 1);
if (topics.length === 0) {
this.c.delete(topic);
}
return true;
}
publish(topic: string, ...args: any[]): any[] | null {
const topics = this.c.get(topic);
if (!topics) {
return null;
}
return topics.map((handler) => {
try {
return handler(...args);
} catch (e) {
console.error(e);
return null;
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment