Skip to content

Instantly share code, notes, and snippets.

@Oobert
Last active January 4, 2016 03:19
Show Gist options
  • Save Oobert/8561325 to your computer and use it in GitHub Desktop.
Save Oobert/8561325 to your computer and use it in GitHub Desktop.
Start of a FSM in JS. Because why not?
var fsm = function (states) {
this.current;
this.states = states;
};
fsm.prototype.changeStateTo = function (newState, obj) {
if (this.current &&
this.current.unload) {
this.current.unload();
}
if (this.states[newState]) {
this.current = this.states[newState];
if (this.current.load) {
this.current.load(obj);
}
}
}
fsm.prototype.callAction = function (action, obj) {
if (this.current[action])
this.current[action](obj);
}
var myFsm = new fsm({
state1:{
StateRealtedObject: {
text: "hello"
},
load: function ()
{
//do work like load template or show/hide page elements
},
StateRelatedFunction: function()
{
//do specific work related to this state.
//can access objects on current state like...
this.StateRelatedObject.text = "hello world";
},
unload: function()
{
//clean up after your self here.
}
},
state2:{
load: function () { },
StateRelatedFunctionOrObjects: function() { },
unload: function(){ }
}
})
myFsm.changeStateTo("state1");
myFsm.callAction("StateRelatedFunction", { /* data in here */ });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment