UNPKG

@xeito/store

Version:

Reactive Stores for Xeito | Framework for building web applications

123 lines (121 loc) 3.28 kB
// packages/store/classes/read-store.ts var ReadStore = class { constructor(value, callback) { this._listeners = /* @__PURE__ */ new Set(); this._value = value; this._callback = callback; } get value() { return this._value; } /** * Sets the value of the store and calls all the listeners * @param value The new value */ set(value) { this._value = value; this._listeners.forEach((listener) => listener(this._value)); } /** * Subscribe to the store * @param listener A function that takes the current value and returns the new value * @returns A subscription object with an unsubscribe method */ subscribe(listener) { if (this._listeners.size === 0) { this._killCallback = this._callback && this._callback(this.set.bind(this)); } listener(this._value); this._listeners.add(listener); return { unsubscribe: () => { this._listeners.delete(listener); if (this._listeners.size === 0) { this._killCallback && this._killCallback(); } } }; } }; // packages/store/classes/write-store.ts var WriteStore = class extends ReadStore { constructor(value, callback) { super(value, callback); } /** * Override the set method to make it public * @param value The new value */ set(value) { super.set(value); } /** * Update method * This method takes a callback function that takes the current value and returns the new value * @param callback A function that takes the current value and returns the new value */ update(callback) { this.set(callback(this._value)); } }; // packages/store/classes/derived-store.ts var DerivedStore = class { constructor(stores, callback, initialValue) { this._listeners = /* @__PURE__ */ new Set(); this._stores = []; this._subscriptions = []; this._values = []; this._value = initialValue; this._callback = callback; this._stores = Array.isArray(stores) ? stores : [stores]; this._stores.forEach((store, index) => { this._subscriptions.push(store.subscribe((value) => { this._values[index] = value; if (this._values.length === this._stores.length) this.runCallback(); })); }); } get value() { return this._value; } subscribe(listener) { listener(this._value); this._listeners.add(listener); return { unsubscribe: () => { this._listeners.delete(listener); if (this._listeners.size === 0) { this._killCallback && this._killCallback(); } } }; } set(value) { this._value = value; this._listeners.forEach((listener) => listener(this._value)); } runCallback() { if (this._killCallback) this._killCallback(); let values = this._values; if (this._stores.length === 1) values = this._values[0]; if (this._callback) { const callbackResult = this._callback(values, this.set.bind(this)); if (callbackResult) { if (typeof callbackResult === "function") { this._killCallback = callbackResult; } else { this.set(callbackResult); } } } } }; export { DerivedStore, ReadStore, WriteStore }; //# sourceMappingURL=index.js.map