get: function (key, sign) {
var result, now = new Date().getTime();
try {
result = this.sProxy.getItem(key);
if (!result) return null;
result = JSON.parse(result);
//数据过期
if (result.timeout < now) return null;
//需要验证签���
if (sign) {
if (sign === result.sign)
return result.value;
return null;
} else {
return result.value;
}
} catch (e) {
console && console.log(e);
}
return null;
},
//获取签名
getSign: function (key) {
var result, sign = null;
try {
result = this.sProxy.getItem(key);
if (result) {
result = JSON.parse(result);
sign = result && result.sign
}
} catch (e) {
console && console.log(e);
}
return sign;
},
remove: function (key) {
return this.sProxy.removeItem(key);
},
clear: function () {
this.sProxy.clear();
}
});
Storage.getInstance = function () {
if (this.instance) {
return this.instance;
} else {
return this.instance = new this();
}
};
return Storage;
});
这段代码包含了localstorage的基本操作,并且对以上问题做了处理,而真实的使用还要再抽象:
define(['AbstractStorage'], function (AbstractStorage) {
var Store = _.inherit({
//默认属性
propertys: function () {
//每个对象一定要具有存储键,并且不能重复
this.key = null;
//默认一条数据的生命周期,S为秒,M为分,D为天
this.lifeTime = '30M';
//默认返回数据
// this.defaultData = null;
//代理对象,localstorage对象
this.sProxy = new AbstractStorage();
},
setOption: function (options) {
_.extend(this, options);
},
assert: function () {
if (this.key === null) {
throw 'not override key property';
}
if (this.sProxy === null) {
throw 'not override sProxy property';
}
},
initialize: function (opts) {
this.propertys();
this.setOption(opts);
this.assert();
},
_getLifeTime: function () {
var timeout = 0;
var str = this.lifeTime;
var unit = str.charAt(str.length - 1);
var num = str.substring(0, str.length - 1);
var Map = {
D: 86400,
H: 3600,
M: 60,
S: 1
};
if (typeof unit == 'string') {
unit = unit.toUpperCase();
}
timeout = num;
if (unit) timeout = Map[unit];
//单位为毫秒
return num * timeout * 1000 ;
},
//缓存数据
set: function (value, sign) {
//获取过期时间
var timeout = new Date();
timeout.setTime(timeout.getTime() + this._getLifeTime());
this.sProxy.set(this.key, value, timeout.getTime(), sign);
},
//设置单个属性
setAttr: function (name, value, sign) {
var key, obj;
if (_.isObject(name)) {
for (key in name) {
if (name.hasOwnProperty(key)) this.setAttr(k, name[k], value);
}
return;
}
if (!sign) sign = this.getSign();