Skip to content

Commit

Permalink
feat: use eventemitter3 in ExternalStore
Browse files Browse the repository at this point in the history
  • Loading branch information
v0l committed Dec 12, 2023
1 parent 8d6cdb3 commit 4ed6ec7
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 19 deletions.
1 change: 1 addition & 0 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
28 changes: 9 additions & 19 deletions packages/shared/src/external-store.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 4ed6ec7

Please sign in to comment.