Created
April 4, 2013 21:01
-
-
Save anonymous/5314313 to your computer and use it in GitHub Desktop.
Example JS state machine, not tested
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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