Skip to content

Latest commit

 

History

History
188 lines (149 loc) · 4.41 KB

states-and-transitions.md

File metadata and controls

188 lines (149 loc) · 4.41 KB

States and Transitions

matter state machine

A state machine consists of a set of states, e.g:

  • solid
  • liquid
  • gas

.. and a set of transitions, e.g:

  • melt
  • freeze
  • vaporize
  • condense
  var fsm = new StateMachine({
    init: 'solid',
    transitions: [hhh
      { name: 'melt',     from: 'solid',  to: 'liquid' },
      { name: 'freeze',   from: 'liquid', to: 'solid'  },
      { name: 'vaporize', from: 'liquid', to: 'gas'    },
      { name: 'condense', from: 'gas',    to: 'liquid' }
    ]
  });

  fsm.state;             // 'solid'
  fsm.melt();
  fsm.state;             // 'liquid'
  fsm.vaporize();
  fsm.state;             // 'gas'

Transition method return value

If a trantion successed, then it return the current state. if it's failed, it return false.

  var fsm = new StateMachine({
    init: 'solid',
    transitions: [hhh
      { name: 'melt',     from: 'solid',  to: 'liquid' },
      { name: 'freeze',   from: 'liquid', to: 'solid'  },
      { name: 'vaporize', from: 'liquid', to: 'gas'    },
      { name: 'condense', from: 'gas',    to: 'liquid' }
    ],
    onTransition: function(event) {
      if (event.from === 'liquid') {
        return false
      }
    }
  });

  fsm.state;             // 'solid'
  fsm.melt();            // 'liquid'
  fsm.state;             // 'liquid'
  fsm.vaporize();        // 'liquid'
  fsm.state;             // 'liquid'

Multiple states for a transition

wizard state machine

If a transition is allowed from multiple states then declare the transitions with the same name:

  { name: 'step',  from: 'A', to: 'B' },
  { name: 'step',  from: 'B', to: 'C' },
  { name: 'step',  from: 'C', to: 'D' }

If a transition with multiple from states always transitions to the same state, e.g:

  { name: 'reset', from: 'B', to: 'A' },
  { name: 'reset', from: 'C', to: 'A' },
  { name: 'reset', from: 'D', to: 'A' }

... then it can be abbreviated using an array of from states:

  { name: 'reset', from: [ 'B', 'C', 'D' ], to: 'A' }

Combining these into a single example:

var fsm = new StateMachine({
  init: 'A',
  transitions: [
    { name: 'step', from: 'A', to: 'B' },
    { name: 'step', from: 'B', to: 'C' },
    { name: 'step', from: 'C', to: 'D' },
    { name: 'reset', from: ['B', 'C', 'D'], to: 'A' },
  ],
})

This example will create an object with 2 transition methods:

  • fsm.step()
  • fsm.reset()

The reset transition will always end up in the A state, while the step transition will end up in a state that is dependent on the current state.