項目地址:https://github.com/WQTeam/web-storage-cache
API說明:https://github.com/WQTeam/web-storage-cache/blob/master/README_zh_CN.md
本人在前端時間做移動端開發想使用localstorage做數據的緩存。發現localstorage只是存儲簡單的string鍵值對。但實際使用中經常要配合JSON.parse 和 JSON.stringify, 在很多場景中又需要添加超時時間。看了一些開源的項目也對localstorage進行了封裝,但都沒有完全復合工作中的業務場景的。所以自己寫了一個。
不知道國內有沒有類似github這種活躍的社區,感覺國內的開源氛圍都不強。
使用:
var wsCache = new WebStorageCache();
// 緩存字符串'wqteam' 到 'username' 中, 超時時間100秒
wsCache.set('username', 'wqteam', {exp : 100});
// 超時截止日期 2015 5 18
wsCache.set('username', 'wqteam', {exp : new Date('2015 5 18')});
// 獲取緩存中 'username' 的值
wsCache.get('username');
// 緩存簡單js對象,默認使用序列化方法為JSON.stringify。可以通過初始化wsCache的時候配置serializer.serialize
wsCache.set('user', { name: 'Wu', organization: 'wqteam'});
// 讀取緩存中的簡單js對象 - 默認使用反序列化方法為JSON.parse。可以通過初始化wsCache的時候配置serializer.deserialize
var user = wsCache.get('user');
alert(user.name + ' belongs to ' + user.organization);
// 刪除緩存中 'username'
wsCache.delete('username');
// 手工刪除所有超時CacheItem,
wsCache.deleteAllExpires();
// 清除客戶端中所有緩存
wsCache.clear();
// 為已存在的(未超時的)緩存值設置新的超時時間。
wsCache.touch('username', 1);
// 如果緩存中沒有key為username2的緩存,則添加username2。反之什么都不做
wsCache.add('username2', 'wqteam', {exp : 1});
// 如果緩存中有key為username的緩存,則替換為新值。反之什么都不做
wsCache.replace('username', 'new wqteam', {exp : 1});
// 檢查當前選擇作為緩存的storage是否被用戶瀏覽器支持。
//如果不支持調用WebStorageCache API提供的方法將什么都不做。
wsCache.isSupported();
API
Constructor
var wsCache = new WebStorageCache({
// [可選] 'localStorage', 'sessionStorage', window.localStorage, window.sessionStorage
// 或者其他實現了 [Storage API] 的storage實例.
// 默認 'localStorage'.
storage: 'localStorage',
// [可選] 類型Number,公共超時事件設置。默認無限大
exp: Infinity
});
isSupported
檢查當前選擇作為緩存的storage是否被用戶瀏覽器支持。 如果不支持調用WebStorageCache API提供的方法將什么都不做。
wsCache.isSupported(); // 返回值Boolean。
set
往緩存中插入數據。
// key [必填] 必須要為String類型。
// value [必填] 支持所以可以JSON.parse 的類型。注:當為undefined的時候會執行 delete(key)操作。
// options [選填] js對象,包含兩個屬性 exp 和 force。
// {
// // 類型Number。超時時間,秒。默認無限大。
// exp: 100,
// // 類型Boolean。為true時:當超過最大容量導致無法繼續插入數據操作時,先清空緩存中已超時的
// // 內容后再嘗試插入數據操作。默認為true。
// force: true
// }
wsCache.set(key, value, options);
get
根據key獲取緩存中未超時數據。返回相應類型String、Boolean、PlainObject、Array的值。
// key [必填] String類型。如果發現該key對應的值已過期,會進行delete(key)操作,返回null。 wsCache.get(key);
delete
根據key刪除緩存中的值。
wsCache.delete(key);
deleteAllExpires
刪除緩存中所有通過WebStorageCache存儲的超時值。
wsCache.deleteAllExpires();
clear
清空緩存中全部的值。注意:這個方法會清除不是使用WebStorageCache插入的值。推薦使用:deleteAllExpires。
wsCache.clear();
touch
根據key為已存在的(未超時的)緩存值以當前時間為基准設置新的超時時間。
// key [必填] String類型 // exp [必填] number 單位:秒 js對象包含exp屬性(以當前時間為起點的新的超時時間) wsCache.touch(key, exp: 1);
add
根據key做插入操作,如果key對應的值不存在或者已超時則插入該值,反之什么都不做。 注:不是通過WebStorageCache插入的值也會當作失效的值,依然執行add操作
wsCache.add(key, value, options);
replace
根據key做插入操作,如果key對應的值存在並且未超時則插入該值,反之什么都不做
注:超時時間以當前時間為基准重新設置。
wsCache.replace(key, value, options);
