Last active
December 20, 2015 17:09
-
-
Save SgtPooki/6167038 to your computer and use it in GitHub Desktop.
Local storage helper AMD module to allow serialization of any data type
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
/** | |
* @fileOverview LocalStorageHelper RequireJS AMD Module File | |
* | |
* @author Russell Dempsey <rdempsey@nerdery.com> | |
* @version 1.0 | |
*/ | |
define(function(require, module, exports) { | |
'use strict'; | |
//includes | |
//var something = require('something'); | |
/** | |
* Constructs a LocalStorageHelper object; | |
* | |
* @name LocalStorageHelper | |
* @class LocalStorageHelper Assists with serializing and deserializing data to localStorage | |
* @constructor | |
* | |
* @since 1.0 | |
*/ | |
var LocalStorageHelper = function() { | |
this.init(); | |
}; | |
var proto = LocalStorageHelper.prototype; | |
/** | |
* Initializes the Module | |
* | |
* @method init | |
* @returns {LocalStorageHelper} | |
* @since 1.0 | |
*/ | |
proto.init = function() { | |
return this; | |
}; | |
/** | |
* Gets the value for the key that was passed. | |
* | |
* @method getValue | |
* @param {String} key The key of some value that's saved in localstorage. | |
* | |
* @return {String|Function|Array|Object|Boolean} The deserialized object from localstorage. | |
*/ | |
proto.getValue = function(key) { | |
var value = localStorage[key]; | |
var result; | |
if (localStorage[key]) | |
{ | |
try { | |
result = JSON.parse(value); | |
} catch(e) { | |
result = value; | |
} | |
} | |
return result; | |
}; | |
/** | |
* Sets the key to the serialized version of value in localstorage, and confirms that it was saved properly. | |
* | |
* @param {String} key A hash key string | |
* @param {String|Function|Array|Object|Boolean} value | |
*/ | |
proto.setValue = function(key, value) { | |
localStorage[key] = JSON.stringify(value); | |
if (this._compare(key, value)) { | |
return true; | |
} else { | |
delete localStorage[key]; | |
return false; | |
} | |
}; | |
/** | |
* | |
* | |
* @method _wasSaved | |
* @param {String} key A hash key string | |
* @param {String|Function|Array|Object|Boolean} value Some value of any type | |
* @return {Boolean} whether or not the deserialized saved value matches the actual value | |
*/ | |
proto._wasSaved = function(key, value) { | |
return this.getValue(key) === value; | |
}; | |
//TODO: add a function to validate keys | |
// Return the module | |
return LocalStorageHelper; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment