Simple State Machine
A simple map-structured state machine in Javascript.
by klenwell
HTML
<div id="sandbox">
<div id="level">
<span class="label">level:</span>
<span id="threat">undefined</span>
</div>
<div class="controls">
<button class="btn" id="raise">raise</button>
<button class="btn" id="lower">lower</button>
</div>
</div>
CSS
#sandbox { padding:20px; }
#sandbox div { margin:8px 0; }
JavaScript
/*
* Klenwell Fiddle: Simple State Machine
* http://jsfiddle.net/klenwell/DRAF8/
*
* For additional fiddles, see:
* http://jsfiddle.net/user/klenwell/fiddles/
*
* http://klenwell.com/is/
*/
var __TITLE__ = 'Simple State Machine'
var __VERSION__ = "1.0";
var States = {
green: {
enter: function(ssm) {
States.enter_state(ssm);
$("#lower").hide();
$("#threat").html("low");
$("#threat").css("color", "green").css("font-weight", "lighter");
},
exit: function(ssm) {
States.exit_state(ssm);
$("#lower").show();
},
lower: function(ssm) {
console.log("can't go any lower than green");
},
raise: function(ssm) {
ssm.change_state("yellow");
},
},
yellow: {
enter: function(ssm) {
States.enter_state(ssm);
$("#threat").html("elevated");
$("#threat").css("color", "goldenrod").css("font-weight", "normal");
},
lower: function(ssm) {
ssm.change_state("green");
},
raise: function(ssm) {
ssm.change_state("red");
},
},
red: {
enter: function(ssm) {
States.enter_state(ssm);
$("#raise").hide();
$("#threat").html("severe");
$("#threat").css("color", "red").css("font-weight", "bold");
},
exit: function(ssm) {
States.exit_state(ssm);
$("#raise").show();
},
lower: function(ssm) {
ssm.change_state("yellow");
},
raise: function(ssm) {
console.log("can't go any higher than red");
},
},
// default callbacks
enter_state: function(ssm) {
console.log('entering state: ' + ssm.state);
},
exit_state: function(ssm) {
console.log('exiting state: ' + ssm.state);
},
pass: function()...