Skip to content

Instantly share code, notes, and snippets.

@jasonbyrne
Forked from johnnycardy/pubsub.ts
Last active November 19, 2020 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonbyrne/43c909bb0b4160a0fc3b6410e3657b57 to your computer and use it in GitHub Desktop.
Save jasonbyrne/43c909bb0b4160a0fc3b6410e3657b57 to your computer and use it in GitHub Desktop.
Simple pub/sub TypeScript class for Angular
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class PubSub {
private topics: { [id: string]: PubSubTopic } = {};
private constructor() {}
public static subscribe(topic: string, listener: (args: any) => void): void {
this.getInstance().subscribeToTopic(topic, listener);
}
public static publish(topic: string, arg: any): void {
this.getInstance().publishToTopic(topic, arg);
}
private static getInstance(): PubSub {
if (!(window as any).myPubSub) {
(window as any).myPubSub = new PubSub();
}
return (window as any).myPubSub;
}
private subscribeToTopic(topic: string, listener: (args: any) => void): void {
this.getTopic(topic).subscribe(listener);
}
public publishToTopic(topic: string, arg: any): void {
this.getTopic(topic).notify(arg);
}
private getTopic(name: string): PubSubTopic {
if (!this.topics.hasOwnProperty(name)) {
this.topics[name] = new PubSubTopic();
}
return this.topics[name];
}
}
class PubSubTopic {
public subscriptions: ((arg: object) => void)[];
private lastArg: object | null = null;
constructor() {
this.subscriptions = [];
}
public subscribe(func: (arg: object) => void): void {
this.subscriptions.push(func);
// Publish the last event for this topic to the new subscription
if (this.lastArg) {
func(this.lastArg);
}
}
public notify(arg: object): void {
this.lastArg = arg;
this.subscriptions.forEach((subscription) => {
subscription(arg);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment