UNPKG

@tinijs/store

Version:

The state management module for the TiniJS framework.

44 lines 1.65 kB
export function createStore(states, options = {}) { const store = new Proxy(states, { get(target, prop) { if (prop === 'subscribe') { return (stateKey, callback) => { if (stateKey in target) { // subscribe const subscriptions = (target[`___${stateKey}$`] ||= new Map()); const subscriptionId = Symbol(); subscriptions.set(subscriptionId, callback); // unsubscribe return () => subscriptions.delete(subscriptionId); } else { throw new Error(`Unknown state: ${stateKey}`); } }; } else if (prop === 'commit') { return (stateKey, value) => (store[stateKey] = value); } else { return target[prop]; } }, set(target, prop, value) { const subscriptions = target[`___${prop}$`]; // set value const currentValue = target[prop]; const oldValue = !options.preserveOldValue ? currentValue : !(currentValue instanceof Object) ? currentValue : structuredClone(currentValue); target[prop] = value; // notify subscribers subscriptions?.forEach(callback => callback(value, oldValue)); // success return true; }, }); return store; } //# sourceMappingURL=main.js.map