Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Event State Machine

Does anybody know of any javascript implementations of a state machine? My goal is to setup a state machine implementation that would bind events to state transitions. So, if a user clicks on a button then the state will be changed, and this state might define certain values in objects to be changed for example.

I want this to be a state machine simply because there will be a rules json file that will allow to dictate what values change of various objects when certain events are called. Because this will be structured within the file, I think it would be easy to parse that information into a state machine object.

like image 575
jab Avatar asked Nov 07 '12 02:11

jab


People also ask

What is state machine in Javascript?

#javascript. A finite state machine is an abstract machine that can have only a fixed number of states. That means it has a fixed number of inputs and a set of outputs. A keyword finite represents that it will have limited options and memory to play with.

Is Redux a state machine?

If you're familiar with Redux, that might look familiar to you. A Redux reducer function is a state machine! A reducer function describes how the machine should transition, given the previous state and an action (aka an event in statechart terminology), to the next state.

What is a state in a state machine?

A state machine reads a set of inputs and changes to a different state based on those inputs. A state is a description of the status of a system waiting to execute a transition. A transition is a set of actions to execute when a condition is fulfilled or an event received.


2 Answers

There are two main libraries for a finite state machine in js :

1/ Machina: Very well documented, examples, supports two JavaScript message bus providers out of the box: postal.js and amplify.js.

2/ Javascript State Machine: simpler and easier to use, perfect for "basic" usages.

like image 158
Benibur Avatar answered Sep 27 '22 22:09

Benibur


I recently built a state machine implementation in JS, which is certainly the easiest to configure, thanks to its transition DSL:

transitions: [   'next    : intro > form > finish',   'back    : intro < form           < error',   'error   :         form >           error',   'restart : intro        < finish' ] 

It's really flexible in both configuration and event handler assignment, you can add and remove states at runtime, pause and resume transitions, hook into a ton of events, with helpers for jQuery and reactive frameworks like Vue:

state-machine-demo

Docs and a whole host of demos here:

  • http://statemachine.davestewart.io
like image 43
Dave Stewart Avatar answered Sep 27 '22 23:09

Dave Stewart