micromachinejs
v1.0.2
Published
Small Finite State Machine implementation in JavaScript.
Downloads
3
Readme
Micromachine.js
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"