1 (function (){ 2 "use strict"; 3 4 //No support for localstorage? Bail out early 5 if(typeof localStorage === "undefined" || typeof JSON === "undefined") 6 { 7 return; 8 } 9 10 //Shortcuts for wrapper 11 var l = localStorage, 12 s = sessionStorage; 13 14 /** 15 * Wrapper for localstorage / sessionstorage data serialization. 16 * Each method has a boolean parameter, that when set as true switches the method 17 * to use sessionStorage rather than the default localStorage. 18 * 19 * @name store 20 * @namespace 21 * @memberOf $_ 22 */ 23 var store = { 24 /** 25 * Retrieves and deserializes a value from localstorage, 26 * based on the specified key 27 * 28 * @param string key 29 * @param bool session 30 * @name get 31 * @memberOf $_.store 32 * @function 33 * @return object 34 * @type object 35 */ 36 get: function (key, sess) 37 { 38 var val = (sess) ? s.getItem(key) : l.getItem(key); 39 40 return JSON.parse(val); 41 }, 42 /** 43 * Puts a value into localstorage at the specified key, 44 * and JSON-encodes the value if not a string 45 * 46 * @param string key 47 * @param mixed value 48 * @param bool session 49 * @name set 50 * @memberOf $_.store 51 * @function 52 */ 53 set: function (key, value, sess) 54 { 55 // Localstorage generally only accepts strings 56 value = JSON.stringify(value); 57 58 (sess) ? s.setItem(key, value) : l.setItem(key, value); 59 }, 60 /** 61 * Removes the specified item from storage 62 * 63 * @param string key 64 * @param bool session 65 * @name remove 66 * @memberOf $_.store 67 * @function 68 */ 69 remove: function (key, sess) 70 { 71 (sess) ? s.removeItem(key) : l.removeItem(key); 72 }, 73 /** 74 * Returns an object of all the raw values in storage 75 * 76 * @param bool session 77 * @name getAll 78 * @memberOf $_.store 79 * @function 80 * @return object 81 * @type object 82 */ 83 getAll: function (sess) 84 { 85 var i, 86 len, 87 data = {}, 88 k, 89 o; 90 91 //Reference to session/localstorage 92 o = (sess) ? l : s; 93 94 len = o.length; 95 96 for (i = 0; i < len; i++) 97 { 98 k = o.key(i); 99 data[k] = o.getItem(k); 100 } 101 102 return data; 103 }, 104 /** 105 * Removes all values from the same domain storage 106 * 107 * @param bool session 108 * @name clear 109 * @memberOf $_.store 110 * @function 111 */ 112 clear: function(sess) 113 { 114 (sess) ? s.clear() : l.clear(); 115 } 116 }; 117 118 $_.ext('store', store); 119 }());