aboutsummaryrefslogtreecommitdiffstats
path: root/admin/themes/default/js/LocalStorageCache.js
blob: 49a4fa98d7d3d903d784c504ecff84b5627be9cd (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
45
46
47
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);
  }
};