From 83770a17b1a0d9ca20594197a2b2b65c052d7d74 Mon Sep 17 00:00:00 2001 From: Michal Szczepanski Date: Thu, 15 Jun 2023 18:41:43 +0200 Subject: [PATCH] feat: convert to singleton --- src/tiny.dispatcher.ts | 21 ++++++++++++++------- tsconfig.json | 1 + 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/tiny.dispatcher.ts b/src/tiny.dispatcher.ts index c939edd..ce513b5 100644 --- a/src/tiny.dispatcher.ts +++ b/src/tiny.dispatcher.ts @@ -7,10 +7,16 @@ const uid = (size = 10): string => { }; export class TinyDispatcher { - private static listeners: { [key: string]: { [key: string]: any } } = {}; - private static once: { [key: string]: string } = {}; + private static instance: TinyDispatcher; + private listeners: { [key: string]: { [key: string]: any } } = {}; + private once: { [key: string]: string } = {}; - static addListener(event: string, handler: (event: string, key: string, value: T) => void, once = false): string { + static getInstance(): TinyDispatcher { + if (!this.instance) this.instance = new TinyDispatcher(); + return this.instance; + } + + addListener(event: string, handler: (event: string, key: string, value: T) => void, once = false): string { if (!this.listeners[event]) { this.listeners[event] = {}; } @@ -20,7 +26,7 @@ export class TinyDispatcher { return key; } - static dispatch(event: string, value?: T): void { + dispatch(event: string, value?: T): void { if (this.listeners[event]) { for (const key in this.listeners[event]) { this.listeners[event][key](event, key, value); // eslint-disable-line @typescript-eslint/no-unsafe-call @@ -32,7 +38,7 @@ export class TinyDispatcher { } } - static removeListener(event: string, key: string): boolean { + removeListener(event: string, key: string): boolean { if (!this.listeners[event]) return false; if (this.listeners[event][key]) { delete this.listeners[event][key]; @@ -41,13 +47,14 @@ export class TinyDispatcher { return false; } - static removeAllListener(event: string): boolean { + removeAllListener(event: string): boolean { if (!this.listeners[event]) return false; delete this.listeners[event]; return true; } - static cleanup() { + cleanup() { this.listeners = {}; + this.once = {}; } } diff --git a/tsconfig.json b/tsconfig.json index 9a8b9eb..8f6fa8b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,6 +4,7 @@ "target": "es2021", "strict": true, "types": ["node"], + "moduleResolution": "node", "typeRoots": ["node_modules/@types", "@types"] } } \ No newline at end of file