aboutsummaryrefslogtreecommitdiffstats
path: root/admin/themes/default/js/LocalStorageCache.js
blob: b720851be7430ff0a0a71f9ab9c7675fc85c9983 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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);
  }
};