Module Index

state.js

import {State} from 'state.js'

Description

State objects are an event-oriented way of managing application state and reacting to changes. It makes use of built-in features such as Proxy and EventTarget to save code and give users less to remember.

By default, state changes are only queued up and processed in a microtask, allowing for batch-processing.
This means that for repeated changes to the same property, the user can decide to process all the changes in one go or even discard everything but the last value of each property.
That way one can easily avoid some types of unnecessary redraws, network requests, etc.

To make code more readable, the constructor defaults to adding an event listener that checks for a method called [prop]Changed in the state object, and calls it with the new value. This behaviour can be disabled by setting the methods option to false.

The state object also has a getter and setter pair for the `state` attribute, which simply accesses this same attribute on the proxy object. This is simply a convenience feature to save some typing on single-variable states.

Options

defer
Set to false to disable deferred change processing. This will emit a new event every time something changes, even if it's about to be changed again in the next line.
methods
Set to false to disable the default event listener that attempts to call a [prop]Changed method on the state object.

Examples

A simple counter state that prints a new count to the console every time it gets updated.

const counter = new State({state: 0}, {defer: false}) counter.stateChanged = (count) => console.log(`new count: ${count}`) counter.state += 1 counter.state += 1 counter.state += 1

This example uses an event listener instead to get notified of all property changes. Collecting changes into a map is an easy way of de-duplicating their values and keeping only the last one.

const state = new State({}, {methods: false}) state.addEventListener("change", event => { console.log(`There were ${event.changes.length} changes.`) new Map(event.changes).forEach((value, prop) => { console.log(`Final vaue of ${prop}: ${value}`) }) }) state.proxy.foo = "foo 1" state.proxy.foo = "foo 2" state.proxy.bar = "bar 1" state.proxy.foo = "foo 3" state.proxy.bar = "bar 2" // There were 5 changes. // Final vaue of foo: foo 3 // Final vaue of bar: bar 2

Storage-backed states

The StorageState subclass of State implements the same API but is backed by a Storage object.

By default, StorageState uses the window.localStorage object, but you can change this by passing the storage option in the constructor.

When using the value short-hand to have a different StorageState for every individual value, these would all override the same key in the storage. To remedy this, the key option can be used to redirect reads and writes of the "value" key to a different key in the storage.

const greeting = new StorageState({}, { storage = sessionStorage, key: 'greeting' }) greeting.valueChanged = newValue => console.log(`Greeting has changed: ${newValue}`) greeting.value = "Hello, World!" console.log(sessionStorage.value) // udnefined console.log(sessionStorage.greeting) // "Hello, World!"

Using a storage object comes with the disadvantage that all values must be stored in a serialised form, which won't work for all data and will break identity. Specifically, all values are converted to JSON strings for storage.

const plainState = new State({}) const storageState = new StorageState({}) const object = {} plainState.value = object storageState.value = object console.log(plainState.value == object) // true console.log(storageState.value == object) // false

Map-backed Storage

When a fallback option is needed, for example to support clients without localStorage without breaking the page, the MapStorage object implements the Storage API and is backed by a plain JavaScript Map object.