Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hierarchical state machines for JavaScript

Ive been super interested in hierarchical state machines particularly in JavaScript and I found this framework and like how it's looks. However I'm not sure if it can perform hierarchical operations.

Does anybody know of solutions alreadyr out there're for hierarchy state machines?

like image 544
Ryan Avatar asked May 04 '12 00:05

Ryan


1 Answers

If you want something like the pattern described in this article, it looks like the framework you linked can do that:

State Machine Classes

You can also turn all instances of a class into an FSM by applying the state machine functionality to the prototype, including your callbacks in your prototype, and providing a startup event for use when constructing instances:

MyFSM = function() {    // my constructor function
  this.startup();
};

MyFSM.prototype = {

  onpanic: function(event, from, to) { alert('panic');        },
  onclear: function(event, from, to) { alert('all is clear'); },

  // my other prototype methods

};

StateMachine.create({
  target: MyFSM.prototype,
  events: [
    { name: 'startup', from: 'none',   to: 'green'  },
    { name: 'warn',    from: 'green',  to: 'yellow' },
    { name: 'panic',   from: 'yellow', to: 'red'    },
    { name: 'calm',    from: 'red',    to: 'yellow' },
    { name: 'clear',   from: 'yellow', to: 'green'  }
  ]});

This should be easy to adjust to fit your appropriate mechanism for object construction.

In other words, at this point you should be able to do the usual JavaScript inheritance thing, something like:

function MyCalmFSM() {
    MyFSM.apply(this, arguments);
}

MyCalmFSM.prototype = Object.create(MyFSM.prototype);
MyCalmFSM.prototype.constructor = MyCalmFSM;

// Don't panic
MyCalmFSM.prototype.onpanic = function(event, from, to) { alert("Don't panic"); }
  
like image 196
Dagg Nabbit Avatar answered Nov 01 '22 11:11

Dagg Nabbit