After reviewing Dustin Diaz’s “JavaScript Cache Provider,” I was unsatisfied with the interface. It required the caller to explicitly state the desire for local storage, as well as remember whether each key stored a string or an object.
I created a simpler interface. Callers can store an object in the cache with only a key and value, and retrieve that value with only the key. By default it uses local storage, if available.
The constructor function takes an optional parameter, so that every call to the CacheStorage instance will either use local storage, or not
[js]
/**
* {Boolean} useLocalStorageIfAvailable - optional, defaults to true. The CacheProvider object will
* use the HTML5 localStorage object, if available
*/
function CacheProvider(useLocalStorageIfAvailable) {
// values will be stored here
this._cache = {};
this._useLocalStorage = 'undefined' == typeof(useLocalStorageIfAvailable) ? true : useLocalStorageIfAvailable;
}
[/js]
Usage is much simpler. For getting an object from cache, just pass the key. CacheProvider will determine whether the saved item was a string or object, all under the covers. To save an item to the cache, just pass in the key and value.
[js]
var cache = new CacheProvider();
// a complex object to test object caching
var obj1 = {
dogs: [
'fido',
'rufus'
],
owner: {
name: 'arod'
}
};
cache.set('key1', obj1);
var obj2 = cache.get('key1');
console.log(obj2);
cache.set('key2', 'asdfasdfasdfd');
var obj3 = cache.get('key2');
console.log(obj3);
cache.clear('key1');
cache.clear('key2');
[/js]
Pingback: JavaScript CacheProvider | Adam Roderick's Blog