Skip to content

Commit

Permalink
fix: createStore
Browse files Browse the repository at this point in the history
  • Loading branch information
djalmajr committed Jun 20, 2023
1 parent e7f9d9f commit 6cedcd7
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/createStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,22 @@ type Store<T> = T & { subscribe(fn: (s: T) => void): () => never };
const { emit, on } = createEmitter();
const { defineProperty, getOwnPropertyDescriptor } = Object;

function handler() {
function handler(uuid: string) {
return {
get(obj: Obj, key: string) {
if (key === '_isProxy') return true;
const d = getOwnPropertyDescriptor(obj, key);
const nok = isObject(obj[key]) && !obj[key]._isProxy && d?.writable;
nok && (obj[key] = new Proxy(obj[key], handler()));
nok && (obj[key] = new Proxy(obj[key], handler(uuid)));
return obj[key];
},
set(obj: Obj, key: string, val: unknown) {
if (obj[key] !== val) (obj[key] = val), emit('update');
if (obj[key] !== val) (obj[key] = val), emit(`update:${uuid}`);
return true;
},
deleteProperty(obj: Obj, key: string) {
delete obj[key];
emit('update');
emit(`update:${uuid}`);
return true;
},
};
Expand All @@ -39,6 +39,7 @@ export function createStore<T extends object>(data: T, opts?: Options): Store<T>
const { immediate } = opts || {};
const fns = <Function[]>[];
const init = clone(data);
const uuid = crypto.randomUUID();

defineProperty(init, 'subscribe', {
value(fn: Function) {
Expand All @@ -51,8 +52,8 @@ export function createStore<T extends object>(data: T, opts?: Options): Store<T>
});

let nextTickId = 0;
const store = new Proxy(init, handler());
on('update', () => {
const store = new Proxy(init, handler(uuid));
on(`update:${uuid}`, () => {
const data = omit('subscribe', store);
if (immediate) return fns.forEach((fn) => fn(data));
if (nextTickId) cancelAnimationFrame(nextTickId);
Expand Down

0 comments on commit 6cedcd7

Please sign in to comment.