Small Finite State Machine implementation in JavaScript.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
dist
docs
src
test
.babelrc
.codeclimate.yml
.eslintrc.js
.gitignore
.travis.yml
README.md
license.md
package.json
webpack.config.babel.js

README.md

Micromachine.js

Build Status npm version Coverage Status Code Climate

This is a small Finite State Machine implementation in JavaScript inspired by a similar library in ruby. The annotated source code is available as documentation.

Installation

$ npm install micromachinejs --save

Usage

Initialize the finite state machine:

// Library is exported as UMD so require it in node.
// In browsers there should be a MicroMachine global.
const MicroMachine = require('micromachinejs');
const initialState = 'unsubmitted';
const fsm = new MicroMachine(initialState);

Define some events:

fsm
  .when('submit', {
    unsubmitted: 'submitted',
    reverted: 'submitted',
  })
  .when('revert', { submitted: 'reverted' })
  .when('approve', { submitted: 'approved' });

Listen to events:

fsm
  .on('submit', (event) => {
    // event.to
    // event.from
    // event.eventName
  })
  .on('submit', (event) => {
    // multiple callbacks to same event are possible
  })
  .on('revert', (event) => {
    // do something else
  })
  .on('any', (event) => {
    // do something when any event is triggered
  });

Trigger an event:

fsm.trigger('submit'); // true
fsm.state; // "submitted"