localStorage对象是HTML5规范中保存在客户端的存储数据,有了它我们可以在H5页面中缓存来自服务器端的数据在本地,从而减少了对服务器的数据请求负担,并使得离线H5应用成为可能。在我们实际应用时,往往需要考虑到本地缓存是否过期的问题,如果缓存已经过期需要重新向服务器请求更新缓存,因此有必要实现带有时间限制的localStorage封装对象,如下:
"use strict"
/*实现带有时间限制的localStorage封装对象*/
function is_undefined(){
for(let index = 0; index < arguments.length; index++){
if(typeof(arguments[index]) === 'undefined'){
return true;
}
}
return false;
}
var timeing_localStorage = {
getItem: function(key){
if(is_undefined(key)){ //检查函数参数是否未定义
throw new Error("arguments of setItem undefined!");
}
var object = JSON.parse(window.localStorage.getItem(key), (key, value) =>{
if(key == 'time'){
return new Date(value);
}else{
return value;
}
});
return object;
},
setItem: function(key,value,date){ //key,value代表键值对,date代表本地缓存创建的时间
if(is_undefined(key,value)){ //检查函数参数是否未定义
throw new Error("arguments of setItem undefined!");
}
if(is_undefined(date)){ //默认为当前时间
date = new Date();
}
if(!(date instanceof Date)){
throw new Error("data type error!");
}
var object = {
value: value,
time: date,
}
window.localStorage.setItem(key, JSON.stringify(object));
},
is_overdue: function(key, timestamp){ //timestamp一般表示服务器数据的更新时间戳,如果比缓存创建时间大说明需要缓存已过期
if(is_undefined(key)){ //检查函数参数是否未定义
throw new Error("arguments of setItem undefined!");
}
if(is_undefined(timestamp)){ //默认为当前时间
timestamp = parseInt(new Date().valueOf() / 1000);
}
if(timestamp < parseInt(this.getItem(key).time.valueOf() / 1000)){
return false;
}
return true;
}
}