JavaScript: Mutables
Normally, only the code block that declares a top-level variable can define it or assign to it. You can however use the Mutable
function to declare a mutable generator, allowing other code to mutate the generator’s value.
Mutable
is available by default in Markdown but you can import it explicitly like so:
import {Mutable} from "npm:@observablehq/stdlib";
Then to use it:
const count = Mutable(0);
const increment = () => ++count.value;
const reset = () => count.value = 0;
In other code, you can now create buttons to increment and reset the count like so:
Inputs.button([["Increment", increment], ["Reset", reset]])
Count is: .
Count is: ${html`<span class="flash">${count}</span>`}.
Within the defining code block, count
is a generator and count.value
can be read and written to as desired; in other code, count
is the generator’s current value. Other code that references count
will re-run automatically whenever count.value
is reassigned — so be careful you don’t cause an infinite loop!