下面我们将增加对象本地存储机制的支持。这个技术是借鉴了Christopher Blizzard的一篇不错的文章 Saving data with local storage – for which those who didn"t know, you can only store string"s into local storage. Thus we have this…
in / out JSON parsing 复制代码 代码如下: if (CacheProvider.hasLocalStorage) { Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); };
Core class functionality 复制代码 代码如下: CacheProvider.prototype = {
/** * {String} k - the key * {Boolean} local - get this from local storage? * {Boolean} o - is the value you put in local storage an object? */ get: function(k, local, o) { if (local && CacheProvider.hasLocalStorage) { var action = o ? "getObject" : "getItem"; return localStorage[action](k) || undefined; } else { return this._cache[k] || undefined; } },
/** * {String} k - the key * {Object} v - any kind of value you want to store * however only objects and strings are allowed in local storage * {Boolean} local - put this in local storage */ set: function(k, v, local) { if (local && CacheProvider.hasLocalStorage) { if (typeof v !== "string")) { // make assumption if it"s not a string, then we"re storing an object localStorage.setObject(k, v); } else { try { localStorage.setItem(k, v); } catch (ex) { if (ex.name == "QUOTA_EXCEEDED_ERR") { // developer needs to figure out what to start invalidating throw new Exception(v); return; } } } } else { // put in our local object this._cache[k] = v; } // return our newly cached item return v; },
/** * {String} k - the key * {Boolean} local - put this in local storage * {Boolean} o - is this an object you want to put in local storage? */ clear: function(k, local, o) { if (local && CacheProvider.hasLocalStorage) { localStorage.removeItem(k); } // delete in both caches - doesn"t hurt. delete this._cache[k]; }
getElementsByClassName 复制代码 代码如下: var cache = new CacheProvider;
window.getElementsByClassName = getElementsByClassName || function(c) { var reg = cache.get(c) || cache.set(c, new RegExp("(?:^|s+)" + c + "(?:s+|$)")); var elements = document.getElementsByTagName("*"); var results = []; for (var i = 0; i < elements.length; i++) { if (elements[i].className.match(reg)) { results.push(elements[i]); } } return results; };
备注:下次你调用类函数的时候, 将会用预先编译好的正则表达式替代够建造一个表达式。
再举一个例子:比如 对于大的应用程序需要i18n,你可以缓存一个编译好的html字符串进入本地存储中。 复制代码 代码如下: var i18nCache = new CacheProvider;