Skip to content

Instantly share code, notes, and snippets.

@jbrooksuk
Created June 28, 2013 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbrooksuk/5883777 to your computer and use it in GitHub Desktop.
Save jbrooksuk/5883777 to your computer and use it in GitHub Desktop.
Selectize Cache Plugin... beginning.
Selectize.registerPlugin('local_storage_cache', function(options) {
var self = this;
var Store = null;
options = $.extend({
lifeTime: -1, // Store forever
keyCacheTimeName: 'meta_ct_',
keyLifeTimeName: 'meta_lt_'
}, options);
var supportsLocalStorage = function() {
if(typeof localStorage === 'undefined' || typeof JSON === 'undefined') {
return false;
}else{
Store = window.localStorage;
return true;
}
};
var cacheItem = function(itemListKey, itemList) {
if(!supportsLocalStorage()) return false;
var keyCacheTimeName = options.keyCacheTimeName + itemListKey,
keyLifeTimeName = options.keyLifeTimeName + itemListKey;
var cacheTime = new Date();
Store.setItem(itemListKey, JSON.stringify(itemList)); // Store the actual data
Store.setItem(keyCacheTimeName, cacheTime.getTime() / 1000); // Store when the cache was created
Store.setItem(keyLifeTimeName, options.lifeTime); // Store how long we want to keep the cache for
return true;
};
var getCachedItem = function(itemListKey) {
if(!supportsLocalStorage()) return false;
// If the value doesn't exist, return false.
if(Store.getItem(itemListKey) === null) return false;
var keyCacheTimeName = options.keyCacheTimeName + itemListKey,
keyLifeTimeName = options.keyLifeTimeName + itemListKey;
var cacheTime = new Date();
if(Store.getItem(itemListKey) === -1) {
return Store.getItem(itemListKey); // Infinite store.
}else{
// Has the data expired? Remove it. It's no longer needed.
if((cacheTime.getTime() / 1000) - Store.getItem(keyCacheTimeName) > Store.getItem(keyLifeTimeName)) {
Store.removeItem(itemListKey);
Store.removeItem(keyCacheTimeName);
Store.removeItem(keyLifeTimeName);
return false;
}
return JSON.parse(Store.getItem(itemListKey));
}
};
hook.after(this, 'load', function() {
// Cache layer
if(this.lastQuery === "") return;
var cachedData = getCachedItem(this.lastQuery);
if($.isEmptyObject(this.options) && !cachedData) {
cacheItem(this.lastQuery, this.options); // Store it.
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment