source: trunk/admin/themes/default/js/LocalStorageCache.js @ 28540

Last change on this file since 28540 was 28540, checked in by mistic100, 10 years ago

feature 3077 : always sort categories by global rank

File size: 1.1 KB
Line 
1var LocalStorageCache = function(options) {
2  this.key = options.key + '_' + options.serverId;
3  this.serverKey = options.serverKey;
4  this.lifetime = options.lifetime ? options.lifetime*1000 : 3600*1000;
5  this.loader = options.loader;
6 
7  this.storage = window.localStorage;
8  this.ready = !!this.storage;
9};
10
11LocalStorageCache.prototype.get = function(callback) {
12  var now = new Date().getTime(),
13      that = this;
14 
15  if (this.ready && this.storage[this.key] != undefined) {
16    var cache = JSON.parse(this.storage[this.key]);
17   
18    if (now - cache.timestamp <= this.lifetime && cache.key == this.serverKey) {
19      callback(cache.data);
20      return;
21    }
22  }
23 
24  this.loader(function(data) {
25    that.set.call(that, data);
26    callback(data);
27  });
28};
29
30LocalStorageCache.prototype.set = function(data) {
31  if (this.ready) {
32    this.storage[this.key] = JSON.stringify({
33      timestamp: new Date().getTime(),
34      key: this.serverKey,
35      data: data
36    });
37  }
38};
39
40LocalStorageCache.prototype.clear = function() {
41  if (this.ready) {
42    this.storage.removeItem(this.key);
43  }
44};
Note: See TracBrowser for help on using the repository browser.