-
-
Save jasonbyrne/43c909bb0b4160a0fc3b6410e3657b57 to your computer and use it in GitHub Desktop.
Simple pub/sub TypeScript class for Angular
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
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