Skip to content

Instantly share code, notes, and snippets.

@Cristy94
Created January 15, 2020 23:48
Show Gist options
  • Save Cristy94/f236605b6154f68709dd4d9de71c1ff4 to your computer and use it in GitHub Desktop.
Save Cristy94/f236605b6154f68709dd4d9de71c1ff4 to your computer and use it in GitHub Desktop.
TypeScript simple global Event System
export const enum EventType {
INFO_UPDATED,
}
type DATA_INFO_UPDATED = string;
type IEventCallback<T> = (data: T) => void;
interface IEventSubscribers {
[eventType: number]: Array<IEventCallback<any>> | undefined;
}
class EventSystem {
private subscribers: IEventSubscribers = {};
public publish(event: EventType.INFO_UPDATED, data: DATA_INFO_UPDATED): boolean;
public publish<T>(event: EventType, data: T): boolean {
const queue = this.subscribers[event];
if (!queue) {
return false;
}
for (const cb of queue) {
cb(data);
}
return true;
}
public subscribe(event: EventType.INFO_UPDATED, callback: IEventCallback<DATA_INFO_UPDATED>): IEventCallback<DATA_INFO_UPDATED>;
public subscribe<T>(event: EventType, callback: IEventCallback<T>): IEventCallback<T> {
if (!this.subscribers[event]) {
this.subscribers[event] = [];
}
this.subscribers[event]!.push(callback);
// Return the callback so we can unsubscribe from it
// This way we can pass an arrow function
return callback;
}
public unsubscribe(event: EventType, callback?: IEventCallback<any>) {
const subs = this.subscribers[event];
if (!subs) {
return;
}
if (!callback) {
this.subscribers[event] = undefined;
} else {
this.subscribers[event] = this.subscribers[event]!.filter((subCb) => {
return subCb !== callback;
});
}
}
}
export const GlobalEvents = new EventSystem();
/** Usage example */
// Subscribe
// const cb = GlobalEvents.subscribe(EventType.INFO_UPDATED, (data) => {
// console.log(data); // {data} already inferred as string
// });
// Publish
// GlobalEvents.publish(EventType.INFO_UPDATED, 'February 1st');
// Unsubscribe
// GlobalEvents.unsubscribe(EventType.INFO_UPDATED, cb);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment