Skip to content

Instantly share code, notes, and snippets.

@etgryphon
Created April 17, 2012 15:39
Show Gist options
  • Save etgryphon/2406924 to your computer and use it in GitHub Desktop.
Save etgryphon/2406924 to your computer and use it in GitHub Desktop.
Statechart loading and login example
app.statechart.addState('marketing', {
enterState: function(){
// TODO: Super Sexy splash screen code...
// Showing marketing material and the login form
},
login: function(){
$.ajax({
type: 'POST',
url: '/',
dataType: "json",
data: $form.serialize(),
complete:function (req) {
if (req.status === 200 || req.status === 304) {
app.statechart.sendEvent('loginSuccessful');
} else {
app.statechart.sendEvent('loginFailed');
}
}
});
this.goToState('loginLoading');
}
});
app.statechart.addState('loginLoading', {
enterState: function(){
// TODO: Super sexy code that shows what you want when trying the login
},
loginSuccessful: function(){
// store the data when you want it: I have a function called
$.ajax({
url: '/api/v1/account',
dataType: 'json',
type: 'GET',
success: function(data) {
app.statechart.sendEvent('accountDataFetchSuccessful', data);
},
error: function(response) {
if (response.status === 406) {
// User is logged out, so keep him on marketing page
app.statechart.sendEvent('accountDataFetchFailed');
}
}
});
},
loginFailed: function(){
// TODO: What happens when the login is wrong?
alert("There was an error logging in. Try again.");
},
accountDataFetchSuccessful: function(data){
var state = app.statechart.getState('base');
state.setData('data', data); // <== this sets data on your state to use...you don't have to do this, you can put it anywhere
this.goToState('base');
},
accountDataFetchFailed: function)(){
// TODO: What happens when the account data is wrong?
}
});
app.statechart.addState('base', { // <== WHAT HAPPEN WHEN YOU LOGIN SUCCESSFULLY
enterState: function(){
var data = this.getData('data') // <== This is the code that you set from above
if (data.welcomeText && data.welcomeText !== '' && data.showWelcomePage === true) {
$('#welcomeMessage').html(data.welcomeText);
}
},
logout: function(){
// TODO: Code that will fire a log out call to the back
this.goToState('logoutState')
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment