Skip to content

Commit

Permalink
[feat]: Add emit
Browse files Browse the repository at this point in the history
  • Loading branch information
Truong Hoang Dung authored and Truong Hoang Dung committed May 9, 2024
1 parent a5ec5f9 commit ab64093
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@revskill10/use-state",
"description": "",
"version": "0.0.2",
"version": "0.0.3",
"author": "",
"license": "",
"keywords": [],
Expand Down
20 changes: 17 additions & 3 deletions src/hooks/use-state/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,19 @@ type Listener = {
unsubscribe: () => void;
};

type EffectHandler<T> = (state: Observable<T>) => void | Promise<void>;
type EventBus<T> = {
emit: (message: keyof T, payload: T[keyof T]) => void;
};

type EffectHandler<T, M> = (
state: Observable<T>,
bus: EventBus<M>
) => void | Promise<void>;

type Config<State, T> = Array<{
handler: HandlerCreator<State, T>;
messages: Array<keyof T>;
onChange?: EffectHandler<State>;
onChange?: EffectHandler<State, T>;
onMount?: (state: Observable<State>) => void;
}>;

Expand All @@ -32,11 +39,18 @@ export function state$<State, T extends Record<keyof T, any>>(
c.handler(state, message);
});

const emit = (message: keyof T, payload: T[keyof T]) => {
eventBus.publish({
payload,
topic: message,
});
};

observe(() => {
for (let i = 0; i < config.length; i++) {
const cfg = config[i];
if (cfg.onChange) {
cfg.onChange(state);
cfg.onChange(state, { emit });
}
}
});
Expand Down

0 comments on commit ab64093

Please sign in to comment.