aboutsummaryrefslogtreecommitdiffstats
path: root/admin/themes/default/js/LocalStorageCache.js
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--admin/themes/default/js/LocalStorageCache.js48
1 files changed, 48 insertions, 0 deletions
diff --git a/admin/themes/default/js/LocalStorageCache.js b/admin/themes/default/js/LocalStorageCache.js
new file mode 100644
index 000000000..49a4fa98d
--- /dev/null
+++ b/admin/themes/default/js/LocalStorageCache.js
@@ -0,0 +1,48 @@
+var LocalStorageCache = function(key, lifetime, loader) {
+ this.key = key;
+ this.lifetime = lifetime*1000;
+ this.loader = loader;
+
+ this.storage = window.localStorage;
+ this.ready = !!this.storage;
+};
+
+LocalStorageCache.prototype.get = function(callback) {
+ var now = new Date().getTime(),
+ that = this;
+
+ if (this.ready && this.storage[this.key] != undefined) {
+ var cache = JSON.parse(this.storage[this.key]);
+
+ if (now - cache.timestamp <= this.lifetime) {
+ callback(cache.data);
+ return;
+ }
+ }
+
+ this.loader(function(data) {
+ if (that.ready) {
+ that.storage[that.key] = JSON.stringify({
+ timestamp: now,
+ data: data
+ });
+ }
+
+ callback(data);
+ });
+};
+
+LocalStorageCache.prototype.set = function(data) {
+ if (this.ready) {
+ that.storage[that.key] = JSON.stringify({
+ timestamp: new Date().getTime(),
+ data: data
+ });
+ }
+};
+
+LocalStorageCache.prototype.clear = function() {
+ if (this.ready) {
+ this.storage.removeItem(this.key);
+ }
+}; \ No newline at end of file