Skip to content

Instantly share code, notes, and snippets.

@johnnycardy
Created July 13, 2020 18:46
Show Gist options
  • Save johnnycardy/e81ad6e8c1a09e9d0c93c60ec95dd970 to your computer and use it in GitHub Desktop.
Save johnnycardy/e81ad6e8c1a09e9d0c93c60ec95dd970 to your computer and use it in GitHub Desktop.
Simple pub/sub TypeScript class
export default 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['PubSub_instance']) {
window['PubSub_instance'] = new PubSub();
}
return window['PubSub_instance'];
}
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;
constructor(){
this.subscriptions = [];
this._lastArg = null;
}
public subscribe(func:(arg:object) => 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