Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example JS state machine, not tested
function magician() {
function MagicStateMachine() {
// State
var currentState = "initial";
var dialog;
var list;
var details;
// Controller
var stateSwitch= {
"initial" : function(event, args) {
switch(event) {
case "start":
showDialog();
currentState = "waiting_for_user";
break;
}
},
"waiting_for_user" : function(event, args) {
switch(event) {
case "got_query":
fetchList();
currentState = "retrieving_list";
break;
case "cancel":
cancel();
currentState = "done";
break;
}
},
"retrieving_list" : function(event, args) {
switch(event) {
case "got_list":
list = args.items;
fetchDetails();
currentState = "retrieving_details";
break;
case "error":
showError(args);
currentState = "done";
break;
}
},
"retrieving_details" : function(event, args) {
switch(event) {
case "got_details":
details = args.details;
showDetails();
currentState = "done";
break;
case "error":
showError(args);
currentState = "done";
break;
}
}
};
function handler(event) {
return function(args) {
stateSwitch[currentState](event, args);
};
}
function showDialog() {
dialog = ...;
dialog.submit.onclick = handler("got_query");
dialog.cancel.onclick = handler("cancel");
dialog.show();
}
function fetchList() {
$.ajax("list?query=" + query)
.done(handler("got_list"))
.fail(handler("error"));
}
function fetchDetails() {
$.ajax("details?id=" + list[0].id)
.done(handler("got_details"))
.fail(handler("error"));
}
function cancel() {
// Too bad
}
function showError(err) {
alert("OMG: " + err);
}
this.start = handler("start");
};
return new MagicStateMachine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.