Files
Piwigo/admin/themes/default/js/LocalStorageCache.js
mistic100 1b60bafb58 feature 3077 : always sort categories by global rank
git-svn-id: http://piwigo.org/svn/trunk@28540 68402e56-0260-453c-a942-63ccdbb3a9ee
2014-05-26 16:56:39 +00:00

44 lines
1.1 KiB
JavaScript

var LocalStorageCache = function(options) {
this.key = options.key + '_' + options.serverId;
this.serverKey = options.serverKey;
this.lifetime = options.lifetime ? options.lifetime*1000 : 3600*1000;
this.loader = options.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 && cache.key == this.serverKey) {
callback(cache.data);
return;
}
}
this.loader(function(data) {
that.set.call(that, data);
callback(data);
});
};
LocalStorageCache.prototype.set = function(data) {
if (this.ready) {
this.storage[this.key] = JSON.stringify({
timestamp: new Date().getTime(),
key: this.serverKey,
data: data
});
}
};
LocalStorageCache.prototype.clear = function() {
if (this.ready) {
this.storage.removeItem(this.key);
}
};