From 4ed6ec7c3df009d9c81d9b3c6422ed1643791699 Mon Sep 17 00:00:00 2001 From: Kieran Date: Tue, 12 Dec 2023 22:47:06 +0000 Subject: [PATCH] feat: use eventemitter3 in ExternalStore --- packages/shared/package.json | 1 + packages/shared/src/external-store.ts | 28 +++++++++------------------ yarn.lock | 1 + 3 files changed, 11 insertions(+), 19 deletions(-) diff --git a/packages/shared/package.json b/packages/shared/package.json index 02e4978b8..6f054de5b 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -16,6 +16,7 @@ "@noble/hashes": "^1.3.2", "@scure/base": "^1.1.2", "debug": "^4.3.4", + "eventemitter3": "^5.0.1", "light-bolt11-decoder": "^3.0.0" }, "devDependencies": { diff --git a/packages/shared/src/external-store.ts b/packages/shared/src/external-store.ts index 21d3f0354..00f0ea722 100644 --- a/packages/shared/src/external-store.ts +++ b/packages/shared/src/external-store.ts @@ -1,27 +1,19 @@ -export type HookFn = (e?: TSnapshot) => void; +import EventEmitter from "eventemitter3"; -export interface HookFilter { - fn: HookFn; +interface ExternalStoreEvents { + change: () => void; } /** - * Simple React hookable store with manual change notifications + * Simple hookable store with manual change notifications */ -export abstract class ExternalStore { - #hooks: Array> = []; +export abstract class ExternalStore extends EventEmitter { #snapshot: TSnapshot = {} as TSnapshot; #changed = true; - hook(fn: HookFn) { - this.#hooks.push({ - fn, - }); - return () => { - const idx = this.#hooks.findIndex(a => a.fn === fn); - if (idx >= 0) { - this.#hooks.splice(idx, 1); - } - }; + hook(cb: () => void) { + this.on("change", cb); + return () => this.off("change", cb); } snapshot(p?: any) { @@ -34,9 +26,7 @@ export abstract class ExternalStore { protected notifyChange(sn?: TSnapshot) { this.#changed = true; - if (this.#hooks.length > 0) { - this.#hooks.forEach(h => h.fn(sn)); - } + this.emit("change"); } abstract takeSnapshot(p?: any): TSnapshot; diff --git a/yarn.lock b/yarn.lock index af8ea47d1..ad3f33493 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2970,6 +2970,7 @@ __metadata: "@scure/base": ^1.1.2 "@types/debug": ^4.1.8 debug: ^4.3.4 + eventemitter3: ^5.0.1 light-bolt11-decoder: ^3.0.0 typescript: ^5.2.2 languageName: unknown