Skip to content

Small Finite State Machine implementation in JavaScript.

License

Notifications You must be signed in to change notification settings

aomran/micromachinejs

Repository files navigation

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"

About

Small Finite State Machine implementation in JavaScript.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published