Skip to content

Reactivity

Brandon Jordan edited this page Sep 7, 2025 · 26 revisions

Stores

Standard Data Store

Spark provides a Store class for data reactivity.

const counter = new Store(initialValue: any)

Set & Update

To modify the value of the store, you can use set() to set the value explicitly.

counter.set(1);

You can also use update() to update the Store based on the current value. It takes a callback that will be provided with the current value of the Store and will set the new value to the value returned from the callback.

countUpButton.onclick = () => {
    counter.update((currentCount) => ++currentCount);
};

Modeling the Value

The Store provides the model() method to subscribe to updates to its value. It accepts a handler that will be provided the initial value of the store, and then any subsequent updates to its value.

counter.model((value) => {
    // ...
});

Binding Elements

You can subscribe to an element in a store.

Automatic

  • For a div, this will automatically model the inner text to the store value.
  • For an input, this will automatically model the input's value to the store value and change the value of the store when the value of that input changes.
  • For a button, this will automatically model the button's text label to the store value.
counter.bind(inputElement);

Custom

You can optionally use a custom handler to update an element based on the value of a store, such as creating an HTML list in an element from an array or object, or hiding an element, etc.

counter.bind(inputElement, (element, value) => element.style.display = value ? 'block' : 'none');

Misc

counter.size(); // Get the length of the value, otherwise returns 0.
counter.empty(); // Returns a boolean based on whether the value is empty.

Spark includes additional types of stores that extend the Store class but model their value based on handling various input.

Clone this wiki locally