Created
June 28, 2013 10:20
Selectize Cache Plugin... beginning.
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
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