In addition to states and transition actions, a state machine can contain arbitrary data and methods:

  var fsm = new StateMachine({
    init: 'A'.transitions: [{name: 'step'.from: 'A'.to: 'B'}].data: {
      color: 'red'
    },
    methods: {
      describe: function() {
        console.log('I am ' + this.color); }}}); fsm.state;// 'A'
  fsm.color;      // 'red'
  fsm.describe(); // 'I am red'
Copy the code

Data and state machine factories

If multiple instances are created from the state machine factory, then the Data object will be shared between them. This is definitely not what you want! To ensure that each instance gets unique data, use a data method instead:

  var FSM = StateMachine.factory({
    init: 'A'.transitions: [{name: 'step'.from: 'A'.to: 'B'}].data: function(color) {      // <-- uses a method that can be called by each instance
      return {
        color: color
      }
    },
    methods: {
      describe: function() {
        console.log('I am ' + this.color); }}});var a = new FSM('red'),
      b = new FSM('blue');

  a.state; // 'A'
  b.state; // 'A'

  a.color; // 'red'
  b.color; // 'blue'

  a.describe(); // 'I am red'
  b.describe(); // 'I am blue'
Copy the code

Note: The parameters used to construct each instance are passed directly to the data method.