feat: use eventemitter3 in ExternalStore

This commit is contained in:
Kieran 2023-12-12 22:47:06 +00:00
parent 8d6cdb3868
commit 4ed6ec7c3d
Signed by: Kieran
GPG Key ID: DE71CEB3925BE941
3 changed files with 11 additions and 19 deletions

View File

@ -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": {

View File

@ -1,27 +1,19 @@
export type HookFn<TSnapshot> = (e?: TSnapshot) => void;
import EventEmitter from "eventemitter3";
export interface HookFilter<TSnapshot> {
fn: HookFn<TSnapshot>;
interface ExternalStoreEvents {
change: () => void;
}
/**
* Simple React hookable store with manual change notifications
* Simple hookable store with manual change notifications
*/
export abstract class ExternalStore<TSnapshot> {
#hooks: Array<HookFilter<TSnapshot>> = [];
export abstract class ExternalStore<TSnapshot> extends EventEmitter<ExternalStoreEvents> {
#snapshot: TSnapshot = {} as TSnapshot;
#changed = true;
hook(fn: HookFn<TSnapshot>) {
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<TSnapshot> {
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;

View File

@ -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