javascript-state-machine
javascript-state-machine copied to clipboard
A javascript finite state machine library
Javascript State Machine
A library for finite state machines.
一个有限状态机库.
查看中文文档
NOTE for existing users
VERSION 3.0 Is a significant rewrite from earlier versions. Existing 2.x users should be sure to read the Upgrade Guide.
值得注意的是VERSION 3.0 已经重写了。 现有2.x用户应该阅读升级指南.
Installation
In a browser:
<script src='https://unpkg.com/@taoqf/javascript-state-machine'></script>
<!-- or -->
<script src='https://unpkg.com/@taoqf/javascript-state-machine/dist/state-machine.min.js'></script>
after downloading the source or the minified version
Using npm:
npm install --save-dev @taoqf/javascript-state-machine
In Node.js:
var StateMachine = require('@taoqf/javascript-state-machine');
Usage
A state machine can be constructed using:
var fsm = new StateMachine('solid',{
melt: { from: 'solid', to: 'liquid' },
freeze: { from: 'liquid', to: 'solid' },
vaporize: { from: 'liquid', to: 'gas' },
condense: { from: 'gas', to: 'liquid' }
},{
on(transition, from, to) {
if(transition === 'melt'){
console.log('I melted');
}
});
... which creates an object with a current state property:
-
fsm.state
... methods to transition to a different state:
-
await fsm.fire('melt')
-
await fsm.fire('freeze')
-
await fsm.fire('vaporize')
-
await fsm.fire('condense')
... along with the following helper methods:
-
fsm.is(s)
- return true if states
is the current state -
fsm.can(t)
- return true if transitiont
can occur from the current state -
fsm.cannot(t)
- return true if transitiont
cannot occur from the current state -
fsm.transitions()
- return list of transitions that are allowed from the current state -
fsm.allTransitions()
- return list of all possible transitions -
fsm.allStates()
- return list of all possible states
Terminology
A state machine consists of a set of States
- solid
- liquid
- gas
A state machine changes state by using Transitions
- melt
- freeze
- vaporize
- condense
A state machine can perform actions during a transition by observing Lifecycle Events
- onBeforeMelt
- onAfterMelt
- onLeaveSolid
- onEnterLiquid
- ...
A state machine can also have arbitrary Data and Methods.
Multiple instances of a state machine can be created using a State Machine Factory.
Documentation
Read more about
- States and Transitions
- Data and Methods
- Lifecycle Events
- Asynchronous Transitions
- Initialization
- Error Handling
- State History
- Visualization
- State Machine Factory
- Upgrading from 2.x
- TypeScript
Contributing
You can Contribute to this project with issues or pull requests.
Release Notes
See RELEASE NOTES file.
License
See MIT LICENSE file.
Contact
If you have any ideas, feedback, requests or bug reports, you can reach me at [email protected]