A value cell is a first-class mutable container for state. It makes reading and updating explicit through val() and update(), replacing an uncontrolled global variable with a small interface. section 18.5
A reactive value cell also keeps watchers: handler functions called when an update produces a different value. This turns “do X after changing the cart” into “when the cart changes, do X.” section 18.6 section 18.7
Use a value cell with a few memorable rules:
- Initialize it with a valid value. section 18.9
- Pass a calculation to update(), not an action; calculate the next value from the current one. section 18.9
- Attach each consequence as a watcher so every kind of state change keeps that consequence current. section 18.7
- Prefer cells for immutable values: they offer safer state handling than regular global variables, though they do not guarantee ordering across timelines. section 18.9
Reactive shopping cart
Represent the cart as ValueCell({}), update it with a function that adds an item, and register update_shipping_icons as a watcher. Adding, removing, or changing quantities then refreshes the icons without repeating that call in every handler. section 18.5 section 18.7
function ValueCell(initialValue) {
var currentValue = initialValue;
var watchers = []; #1
return {
val: function() {
return currentValue;
},
update: function(f) {
var oldValue = currentValue;
var newValue = f(oldValue);
if(oldValue !== newValue) {
currentValue = newValue;
forEach(watchers, function(watcher) { #2
watcher(newValue);
});
}
},
addWatcher: function(f) { #3
watchers.push(f);
}
};
}
Inspect the compact implementation that stores watchers, compares old and new values, and invokes each watcher after a change. section 18.6
