自我到期的LocalStorage记录

时间:2015-03-02 10:14:05

标签: jquery local-storage

设置具有自身过期时间戳的LocalStorage记录时出现问题,以避免对我的服务器进行大量查询。我有一个动态内容div:

 <div id="storage"><p>Dynamic content</p></div>

并希望将其内容添加到我的localStorage中5分钟。如果此记录不到5分钟,我不想从服务器获取内容并从localStorage中获取保存的内容。但如果超过5分钟,则应删除localStorage记录,并从服务器中提取新内容并保存为新记录。请参阅下面的jQuery代码:

$(function () {
     function now() {
         return +new Date
     }
     var db = window.db = {
         get: function (key) {
             var entry = JSON.parse(localStorage.getItem(key) || "0");
             if (!entry) return null;
             if (entry.ttl && entry.ttl + entry.now < now()) {
                 localStorage.removeItem(key);
                 return null;
             }
             return entry.value;
         },
         set: function (key, value, ttl) {
             localStorage.setItem(key, JSON.stringify({
                 ttl: ttl || 0,
                 now: now(),
                 value: value
             }));
         }
     };
 });

 $(function () {
     // Set Value with TTL of 50 Secionds using Milliseconds.
     db.set("homeStorage", $("#storage").html(), 50000);
 });

 $(function () {
     var contentsOfNews = db.get("homeStorage");
     $("#storage").html(contentsOfNews);
 });

目前,每次更新内容时都会设置内容。

请在此处查看jsfiddle:http://jsfiddle.net/owvtauuj/

尝试手动更新div#storage的内容,看看我的意思。

1 个答案:

答案 0 :(得分:0)

我通过添加属性来解决此问题以保存过期时间。

也许你可以尝试这个web-storage-cache

var defaultSerializer = {
        serialize: function (item) {
            return JSON.stringify(item);
        },
        // fix for "illegal access" error on Android when JSON.parse is
        // passed null
        deserialize: function (data) {
            return data && JSON.parse(data);
        }
    };

function _getExpiresDate (expires, now) {
        now = now || new Date();

        if (typeof expires === 'number') {
            expires = expires === Infinity ?
            _maxExpireDate : new Date(now.getTime() + expires * 1000);
        } else if (typeof expires === 'string') {
            expires = new Date(expires);
        }

        if (expires && !_isValidDate(expires)) {
            throw new Error('`expires` parameter cannot be converted to a valid Date instance');
        }

        return expires;
    }

function _isValidDate (date) {
        return Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime());
    }

function _extend (obj, props) {
        for (var key in props) obj[key] = props[key];
        return obj;
    }

// item Constructor

function CacheItemConstructor (value, exp) {
  // createTime
  this.c = (new Date()).getTime();
  exp = exp || _maxExpireDate;
  var expires = _getExpiresDate(exp);
  // expiresTime
  this.e = expires.getTime();
  this.v = value;
}

function expiresSet(key, val, options) {

            if (typeof key !== 'string') {
                console.warn(key + ' used as a key, but it is not a string.');
                key = String(key);
            }

            options = _extend({force: true}, options);

            if (val === undefined) {
                return this.delete(key);
            }

            var value = defaultSerializer.serialize(val);

            var cacheItem = new CacheItemConstructor(value, options.exp);
            
           localStorage.setItem(key, defaultSerializer.serialize(cacheItem));
           
        }

// get Item

function expiresGet(key) {
        var cacheItem = defaultSerializer.deserialize(localStorage.getItem(key));
        if(cacheItem != null) {
            var timeNow = (new Date()).getTime();
            if(timeNow < cacheItem.e) {
                var value = cacheItem.v;
                return defaultSerializer.deserialize(value);
            } else {
                localStorage.removeItem(key);
            }
        }
        return null;
}


// Test
expiresSet('mykey', {name: 'tim', age: 10}, {exp: 5});

console.log(expiresGet('mykey'));

setTimeout(function() {
  console.log(expiresGet('mykey'));
}, 5000);