state-management-utilities
Version:
State management utilities
35 lines (34 loc) • 1.07 kB
JavaScript
import { StateManager } from "./state-manager";
export class Computed 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,
},
});
}
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;