Skip to content

Instantly share code, notes, and snippets.

@dylants
Created January 7, 2014 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylants/8307628 to your computer and use it in GitHub Desktop.
Save dylants/8307628 to your computer and use it in GitHub Desktop.
JavaScript client side application state, using session storage.
/*global define:true, sessionStorage:true*/
define([
"underscore"
], function(_) {
"use-strict";
var appState, sessionStorageNamespace;
sessionStorageNamespace = "app.appState";
function AppState(supportSessionStorage) {
this.supportSessionStorage = supportSessionStorage;
this.myId = null;
}
AppState.prototype.getMyId = function() {
return this.myId;
};
AppState.prototype.setMyId = function(myId) {
this.myId = myId;
this.persist();
};
AppState.prototype.persist = function() {
// if we support session storage, persist ourselves
if (this.supportSessionStorage) {
sessionStorage.setItem(sessionStorageNamespace, JSON.stringify(this));
}
};
if (typeof sessionStorage != "undefined") {
// attempt to load from the session storage
appState = sessionStorage.getItem(sessionStorageNamespace);
if (appState) {
appState = _.extend(new AppState(true), JSON.parse(appState));
} else {
// it wasn't found, but we do support session storage
appState = new AppState(true);
}
} else {
// we don't support session storage
appState = new AppState(false);
}
return appState;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment