Created
August 9, 2010 21:24
-
-
Save lorennorman/516155 to your computer and use it in GitHub Desktop.
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
// Create a quick singleton object to represent our mock mobile app | |
var App = {}; | |
// Our App has many states and state-change callbacks | |
App.currentState = null; | |
App.STATES = [ | |
{name: 'main_menu'}, | |
{name: 'loading'}, | |
{ | |
name: 'list_doables', | |
onEnter: function() | |
{ | |
$.each(App.doables, function(index, doable) | |
{ | |
var label = $('<li>'+doable.name+'</li>'); | |
if(doable.status[0] == 'available') | |
{ | |
var doItButton = $('<input type="button" value="Do It!"/>') | |
label.append(doItButton); | |
doItButton.click(function() | |
{ | |
App.changeState('loading'); | |
Data.doDoable(doable.id, function(data) | |
{ | |
App.changeState('done'); | |
}); | |
}); | |
} | |
else | |
{ | |
label.append(' ('+doable.status[0]+')'); | |
} | |
$('#doables').append(label); | |
}); | |
}, | |
onExit: function() | |
{ | |
$('#doables li').remove(); | |
} | |
}, | |
{ | |
name: 'list_awards', | |
onEnter: function() | |
{ | |
$.each(App.awards, function(index, award) | |
{ | |
var label = $('<li>'+award.award_type.name+' - '+award.user+'</li>'); | |
$('#awards').append(label); | |
}); | |
}, | |
onExit: function() | |
{ | |
$('#awards li').remove(); | |
} | |
}, | |
{name: 'done'} | |
]; | |
// The changeState manages our states and transitions. It: | |
// - looks up the new state (does nothing if it can't find it) | |
// - hides the old state | |
// - runs the old state's onExit function | |
// - runs the new state's onEnter function | |
// - shows the new state | |
App.changeState = function(newStateName) | |
{ | |
// Find the State | |
$.each(App.STATES, function(index, value) | |
{ | |
if(value.name == newStateName) | |
{ | |
var newState = value; | |
// Hide the old state and call onExit callback | |
if(App.currentState) | |
{ | |
$('#'+App.currentState.name).hide(); | |
App.currentState.onExit && App.currentState.onExit(); | |
} | |
// Execute the onEnter callback if it exists | |
newState.onEnter && newState.onEnter(); | |
// Show and remember the new state | |
$('#'+newState.name).show(); | |
App.currentState = newState; | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment