forked from Kieran/snort
feat: use eventemitter3 in ExternalStore
This commit is contained in:
parent
8d6cdb3868
commit
4ed6ec7c3d
@ -16,6 +16,7 @@
|
|||||||
"@noble/hashes": "^1.3.2",
|
"@noble/hashes": "^1.3.2",
|
||||||
"@scure/base": "^1.1.2",
|
"@scure/base": "^1.1.2",
|
||||||
"debug": "^4.3.4",
|
"debug": "^4.3.4",
|
||||||
|
"eventemitter3": "^5.0.1",
|
||||||
"light-bolt11-decoder": "^3.0.0"
|
"light-bolt11-decoder": "^3.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
@ -1,27 +1,19 @@
|
|||||||
export type HookFn<TSnapshot> = (e?: TSnapshot) => void;
|
import EventEmitter from "eventemitter3";
|
||||||
|
|
||||||
export interface HookFilter<TSnapshot> {
|
interface ExternalStoreEvents {
|
||||||
fn: HookFn<TSnapshot>;
|
change: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple React hookable store with manual change notifications
|
* Simple hookable store with manual change notifications
|
||||||
*/
|
*/
|
||||||
export abstract class ExternalStore<TSnapshot> {
|
export abstract class ExternalStore<TSnapshot> extends EventEmitter<ExternalStoreEvents> {
|
||||||
#hooks: Array<HookFilter<TSnapshot>> = [];
|
|
||||||
#snapshot: TSnapshot = {} as TSnapshot;
|
#snapshot: TSnapshot = {} as TSnapshot;
|
||||||
#changed = true;
|
#changed = true;
|
||||||
|
|
||||||
hook(fn: HookFn<TSnapshot>) {
|
hook(cb: () => void) {
|
||||||
this.#hooks.push({
|
this.on("change", cb);
|
||||||
fn,
|
return () => this.off("change", cb);
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
const idx = this.#hooks.findIndex(a => a.fn === fn);
|
|
||||||
if (idx >= 0) {
|
|
||||||
this.#hooks.splice(idx, 1);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
snapshot(p?: any) {
|
snapshot(p?: any) {
|
||||||
@ -34,9 +26,7 @@ export abstract class ExternalStore<TSnapshot> {
|
|||||||
|
|
||||||
protected notifyChange(sn?: TSnapshot) {
|
protected notifyChange(sn?: TSnapshot) {
|
||||||
this.#changed = true;
|
this.#changed = true;
|
||||||
if (this.#hooks.length > 0) {
|
this.emit("change");
|
||||||
this.#hooks.forEach(h => h.fn(sn));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract takeSnapshot(p?: any): TSnapshot;
|
abstract takeSnapshot(p?: any): TSnapshot;
|
||||||
|
@ -2970,6 +2970,7 @@ __metadata:
|
|||||||
"@scure/base": ^1.1.2
|
"@scure/base": ^1.1.2
|
||||||
"@types/debug": ^4.1.8
|
"@types/debug": ^4.1.8
|
||||||
debug: ^4.3.4
|
debug: ^4.3.4
|
||||||
|
eventemitter3: ^5.0.1
|
||||||
light-bolt11-decoder: ^3.0.0
|
light-bolt11-decoder: ^3.0.0
|
||||||
typescript: ^5.2.2
|
typescript: ^5.2.2
|
||||||
languageName: unknown
|
languageName: unknown
|
||||||
|
Loading…
Reference in New Issue
Block a user