UNPKG

@dhmk/atom

Version:

Lightweight mobx-like observable values, computed values and side-effects

62 lines (61 loc) 2.22 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import { useAtom } from "../shared"; import { AtomState, Id, defaultAtomOptions, } from "../types"; import { runtime } from "../runtime"; var ValueAtom = /** @class */ (function () { function ValueAtom(value, options) { this.value = value; this.observers = new Map(); this.runId = new Id(); this.versionId = new Id(); this.isObserved = false; this.options = __assign(__assign({}, defaultAtomOptions), options); } ValueAtom.prototype.invalidate = function () { this.observers.forEach(function (_, a) { return a.invalidate(AtomState.Stale, true); }); runtime.runEffects(); }; ValueAtom.prototype.set = function (x) { if (runtime.requireAction && !runtime.counter) throw new Error("Attempted to set atom value outside action."); if (this.options.equals(x, this.value)) return; this.value = x; this.versionId = new Id(); this.invalidate(); }; ValueAtom.prototype.actualize = function () { }; ValueAtom.prototype.get = function () { useAtom(this); if (!this.isObserved && runtime.currentAtom) { this.isObserved = true; var onBO = this.options.onBecomeObserved; if (onBO) runtime.addEffect({ actualize: onBO }); } return this.value; }; ValueAtom.prototype.toJSON = function () { return this.get(); }; ValueAtom.prototype.dispose = function () { if (this.isObserved) { this.isObserved = false; var onBUO = this.options.onBecomeUnobserved; if (onBUO) runtime.addEffect({ actualize: onBUO }); } }; return ValueAtom; }()); export { ValueAtom };