2012-09-04 15 views

回答

1

沒有,simple-storage和DOM Storage是完全不同的事情這意味着你不能使用像jStorage這是指與DOM存儲工作的圖書館。

話又說回來,存儲JSON和實現TTL是很簡單的自己實現。對於JSON,您使用JSON.parseJSON.stringify。對於TTL,只需將TTL值存儲在某個地方,並在必要時查看它們。事情是這樣的:

var AdvancedStorage = { 
    _storage: require("simple-storage").storage, 

    // Keep TTL data in a special storage field 
    _ttlData: null, 
    _readTTLData() { 
    if (this._storage._ttl) 
     this._ttlData = JSON.parse(this._storage._ttl); 
    else 
     this._ttlData = {}; 
    }, 
    _saveTTLData() { 
    this._storage._ttl = JSON.stringify(this._ttlData); 
    }, 

    // Special data manipulation functions 
    set: function(key, value, options) { 
    this._storage[key] = JSON.stringify(value); 
    this.setTTL(key, options && "TTL" in options ? options.TTL : 0); 
    }, 

    get: function(key, default) { 
    if (!this._storage.hasOwnProperty(key)) 
     return default; 

    // Check whether setting has expired 
    if (!this._ttlData) 
     this._readTTLData(); 
    if (this._ttlData.hasOwnProperty(key) && this._ttlData[key] <= Date.now()) 
     return default; 

    return JSON.parse(this._storage[key]); 
    }, 

    deleteKey: function(key) { 
    delete this._storage[key]; 
    }, 

    // Setting the TTL value 
    setTTL(key, ttl) { 
    if (!this._ttlData) 
     this._readTTLData(); 
    if (ttl > 0) 
     this._ttlData[key] = Date.now() + ttl; 
    else 
     delete this._ttlData[key]; 
    this._saveTTLData(); 
    } 
}; 

我沒有測試此代碼,但是這應該是幾乎所有你需要實現這種功能的代碼。