Skip to content

Class-based

ixfx’s StateMachine.WithEvents which wraps the functional implementation described above and also provides events for listening for event changes.

The same format is used to define possible transitions. Now there’s an mutable object, so const can be used:

import { StateMachine } from "https://unpkg.com/ixfx/dist/flow.js"
const definition = {
sleep: `wakeup`,
wakeup: [`coffee`, `breakfast`],
coffee: `bike`,
breakfast: `bike`,
bike: null
}
const sm = new StateMachine.WithEvents(definition, { initial: `sleep` });

Change the state by name:

sm.state = `wakeup`

In some cases, you might want to ask the machine to transition to its next possible state, regardless of its current state. If multiple states are possible, it will use the first one.

sm.next();

Reset the machine back to its initial state with reset . This is the only way to continue after reaching the final state.

sm.reset();

Check status

if (sm.state === `coffee`) ...
if (sm.isDone) ...

The change event is fired whenever state changes, and stop when the machine reaches a final state.

sm.addEventListener(`change`, (evt) => {
console.log(`State change from ${evt.priorState} -> ${evt.newState}`);
// Prints for example:
// State change from wakeup -> breakfast
});
sm.addEventListener(`stop`, (evt) => {
console.log(`Machine has finished in state: ${evt.newState}`);
});