Skip to content

Instantly share code, notes, and snippets.

@dgowrie
Created January 30, 2015 04:52
Show Gist options
  • Select an option

  • Save dgowrie/959708a5649cfa43b567 to your computer and use it in GitHub Desktop.

Select an option

Save dgowrie/959708a5649cfa43b567 to your computer and use it in GitHub Desktop.
Local Storage example, structured with the Revealing Prototype Pattern for a "Class" like usage, also namespaced
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Localstorage demo</title>
</head>
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script src="Scripts/LocalStorageUtility.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var ls = new AppUtils.LocalStorageUtility(["Name", "City"], ["tbName", "tbCity"], "lblFeedback");
if (ls.HasLocalStorage) {
$("#lblFeedback").text("Local storage is enabled!");
}
else {
$("#lblFeedback").text("Local storage is disabled!");
}
$("#btnLoadSettings").click(function () { ls.LoadSettings(ls); });
$("#btnSaveSettings").click(function () { ls.StoreSettings(ls); });
$("#btnClearSettings").click(ls.ClearSettings);
});
</script>
<body>
<table>
<tr>
<td>Name</td><td><input id="tbName" type="text" /></td>
<td>City</td><td><input id="tbCity" type="text" /></td>
</tr>
</table>
<button id="btnLoadSettings" type="button">Load settings</button>
<button id="btnSaveSettings" type="button">Save settings</button>
<button id="btnClearSettings" type="button">Clear settings</button>
<p id="lblFeedback" style="color: darkgreen">ready</p>
</body>
</html>
var AppUtils = AppUtils || {};
AppUtils.LocalStorageUtility = function(storageKeys, sourceElements, feedbackElement) {
this.storageKeys = storageKeys;
this.sourceElements = sourceElements;
this.feedbackElement = feedbackElement;
};
AppUtils.LocalStorageUtility.prototype = (function () {
var storeSettings = function (thisObj) {
for (var i = 0; i < thisObj.storageKeys.length; i++) {
var storageKey = thisObj.storageKeys[i];
var elementName = thisObj.sourceElements[i];
localStorage.setItem(storageKey, $("#" + elementName).val());
}
$("#" + thisObj.feedbackElement).text("Local setting saved!");
},
loadSettings = function (thisObj) {
for (var i = 0; i < thisObj.storageKeys.length; i++) {
var storageKey = thisObj.storageKeys[i];
var elementName = thisObj.sourceElements[i];
$("#" + elementName).val(localStorage.getItem(storageKey));
}
$("#" + thisObj.feedbackElement).text("Local setting loaded!");
},
clearSettings = function () {
localStorage.clear();
},
hasLocalStorage = function () {
return typeof (Storage) !== "undefined";
}
return {
StoreSettings: storeSettings,
LoadSettings: loadSettings,
ClearSettings: clearSettings,
HasLocalStorage: hasLocalStorage
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment