UNPKG

state-management-utilities

Version:
43 lines (42 loc) 1.28 kB
import { StateManager } from "./state-manager"; export class ComputedManager extends StateManager { get value() { return this._clone(this._value); } set value(_) { throw new Error("Computed state manager value cannot be set directly.", { cause: { uid: this.uid, }, }); } update(updater) { throw new Error("Computed state manager value cannot be set directly.", { cause: { uid: this.uid, }, }); return this; } constructor(callback, triggers, config = { uid: `CSM-${++counter}`, }) { if (typeof callback !== "function") { throw new Error("Computed state manager callback must be a function."); } const initialValue = callback(); if (initialValue instanceof Promise) { throw new Error("Computed state manager callback must not return a promise."); } super(initialValue, config); triggers.forEach((trigger) => { trigger.register({ uid: this.uid, callback: async () => { this._setValueHandler(callback()); }, }); }); } } let counter = 0;