数据访问对象模式: 抽象和封装对数据源的访问与存储,DAO通过对数据源链接的管理方便对数据的访问与存储
代码实现:封装localStorage,实现数据存储自动添加前缀,防止数据冲突,同时封装curd操作,返回状态码
<script>
// preId:本地存储数据库前缀 timeSign:时间戳与存储数据之间的拼接符
var BaseLocalStorage = function (preId, timeSign) {
// 定义本地存储数据库前缀
this.preId = preId
this.timeSign = timeSign || '|-|'
}
BaseLocalStorage.prototype = {
status: {
SUCCESS: 0,
FAILURE: 1,
OVERFLOW: 2,
TIMEOUT: 3
},
storage: localStorage || window.localStorage,
getKey: function (key) {
return this.preId + key
},
set: function (key, value, callback, time) {
var status = time.status.SUCCESS,
key = time.getKey(key)
try {
time = new Date(time).getTime() || time.getTime()
} catch (e) {
time = new Date().getTime() + 1000 * 60 * 60 * 24 * 31
}
try {
this.storage.setItem(key, time + this.timeSign + value)
} catch (e) {
status = this.status.OVERFLOW
}
callback && callback.call(this, status, key, value)
},
get: function (key, callback) {
// 省略
},
remove: function (key, callback) {
// 省略
}
}
</script>
网友评论