MobX-style observable state with autorun dependency tracking
Libraries such as MobX and Vue keep the UI in sync without manual subscriptions: you read state inside an effect, and the effect reruns whenever something it read changes. Implement a small version of that engine as an object named reactivity with three methods.
const store = reactivity.observable(source); // an observable version of a plain object
const dispose = reactivity.autorun(effect); // runs effect now and after relevant changes
const result = reactivity.batch(fn); // groups writes; returns fn()
observable(source)source is a plain object. Return an object with the same properties that you can read and write normally (store.count, store.count = 2, delete store.count). You may wrap source (for example with a Proxy) or copy it; tests only use the returned object.store.user === store.user. A plain object assigned later (store.user = { ... }) becomes observable when read.Map, or Set).autorun(effect)effect() immediately. While it runs, every property read on any observable (store.key or store[key]) makes the autorun depend on that property of that object. Reading a property that does not exist yet counts too.Object.is), when a new property is added, or when an existing property is deleted. Assigning the same value is not a change.dispose function. After it is called the effect never runs again, even if a change is waiting in a batch. Calling it twice is harmless.batch(fn)fn() and return its result. Changes made inside do not rerun autoruns right away. When fn finishes, each affected autorun runs once, seeing the final values.fn throws, the affected autoruns still run, then the error is rethrown.const cart = reactivity.observable({ items: 2, price: 10, coupon: null });
const totals = [];
const dispose = reactivity.autorun(() => {
totals.push(cart.items * cart.price);
});
// totals => [20]
cart.items = 3; // totals => [20, 30]
cart.items = 3; // same value, no rerun
cart.coupon = 'SAVE10'; // not read by the effect, no rerun
reactivity.batch(() => {
cart.items = 1;
cart.price = 50;
});
// totals => [20, 30, 50] (one rerun for two writes)
dispose();
cart.items = 9; // no rerun
Keep the line export default reactivity;: tests call reactivity.observable, reactivity.autorun, and reactivity.batch.