Skip to content

Commit

Permalink
Rename createStore to createState
Browse files Browse the repository at this point in the history
  • Loading branch information
djalmajr committed Aug 4, 2023
1 parent 6480001 commit 8339f5d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
25 changes: 16 additions & 9 deletions src/createStore.ts → src/createState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import { omit } from './omit';
import { guid } from './random';
import { Obj } from './types';

type Store<T> = T & { subscribe(fn: (s: T) => void): () => never };
type Store<T> = T & {
dispose(fn: (s: T) => void): void;
observe(fn: (s: T) => void): () => void;
};

const { emit, on } = createEmitter();
const { defineProperty, getOwnPropertyDescriptor } = Object;
Expand Down Expand Up @@ -36,26 +39,30 @@ type Options = {
immediate?: boolean;
};

export function createStore<T extends object>(data: T, opts?: Options): Store<T> {
export function createState<T extends object>(data?: T, opts?: Options): Store<T> {
const { immediate } = opts || {};
const fns = <Function[]>[];
const init = clone(data);
const init = clone(data || {}) as Obj;
const uid = guid();

defineProperty(init, 'subscribe', {
defineProperty(init, 'dispose', {
value(fn: Function) {
const idx = fns.findIndex((f) => f === fn);
idx !== -1 && fns.splice(idx, 1);
},
});

defineProperty(init, 'observe', {
value(fn: Function) {
if (!fns.includes(fn)) fns.push(fn);
return () => {
const idx = fns.findIndex((l) => l === fn);
idx !== -1 && fns.splice(idx, 1);
};
return () => init.dispose(fn);
},
});

let nextTickId = 0;
const store = new Proxy(init, handler(uid));
on(`update:${uid}`, () => {
const data = omit('subscribe', store);
const data = omit(['dispose', 'observe'], store);
if (immediate) return fns.forEach((fn) => fn(data));
if (nextTickId) cancelAnimationFrame(nextTickId);
nextTickId = requestAnimationFrame(() => fns.forEach((fn) => fn(data)));
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export * from './copy';
export * from './createAjax';
export * from './createCache';
export * from './createEmitter';
export * from './createStore';
export * from './createState';
export * from './curry';
export * from './debounce';
export * from './diff';
Expand Down

0 comments on commit 8339f5d

Please sign in to comment.