-
Notifications
You must be signed in to change notification settings - Fork 1
/
网页state持久化.html
164 lines (157 loc) · 3.9 KB
/
网页state持久化.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
<!DOCTYPE html>
<html>
<head>
<title>_state持久化</title>
<style type="text/css">
</style>
</head>
<body>
<script type="text/javascript">
/*
持久化相关内容
*/
// 重写的Array方法
const funcArr = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse']
const typeArr = ['object', 'array']
// 各级指向父节点和及父节点名字的项
const pointerParent = Symbol('parent')
const poniterKey = Symbol('key')
function setCallBack(obj, key, options) {
if (options && options.set) {
if (getType(options.set) !== 'function') throw ('options.set需为function')
options.set(obj, key)
}
}
function rewriteArrFunc(arr, options) {
if (getType(arr) !== 'array') throw ('参数需为array')
funcArr.forEach(key => {
arr[key] = function(...args) {
this.__proto__[key].apply(this, args)
setCallBack(this[pointerParent], this[poniterKey], options)
}
})
}
function dep(obj, key, options) {
let data = obj[key]
if (typeArr.includes(getType(data))) {
data[pointerParent] = obj
data[poniterKey] = key
}
Object.defineProperty(obj, key, {
configurable: true,
get() {
if (options && options.get) {
options.get(obj, key)
}
return data
},
set(val) {
if (val === data) return
data = val
let index = typeArr.indexOf(getType(data))
if (index >= 0) {
data[pointerParent] = obj
data[poniterKey] = key
if (index) {
rewriteArrFunc(data, options)
} else {
observer(data, options)
}
}
setCallBack(obj, key, options)
}
})
}
function observer(obj, options) {
if (getType(obj) !== 'object') throw ('参数需为object')
let index
Object.keys(obj).forEach(key => {
dep(obj, key, options)
index = typeArr.indexOf(getType(obj[key]))
if (index < 0) return
if (index) {
rewriteArrFunc(obj[key], options)
} else {
observer(obj[key], options)
}
})
}
function getStoragePath(obj, key) {
let storagePath = [key]
while (obj) {
if (obj[poniterKey]) {
key = obj[poniterKey]
storagePath.unshift(key)
}
obj = obj[pointerParent]
}
return storagePath
}
function debounceStorage(state, fn, delay) {
if(getType(fn) !== 'function') return null
let updateItems = new Set()
let timer = null
return function setToStorage(obj, key) {
let changeKey = getStoragePath(obj, key)[0]
updateItems.add(changeKey)
clearTimeout(timer)
timer = setTimeout(() => {
try {
updateItems.forEach(key => {
fn.call(this, key, JSON.stringify(state[key]))
})
updateItems.clear()
} catch(e) {
console.error(`persistent.js中state内容持久化失败,错误位于[${changeKey}]参数中的[${key}]项`)
}
}, delay)
}
}
function persistedState({state, setItem, getItem, setDelay=0}) {
if(getType(getItem) === 'function') {
// 初始化时将storage中的内容填充到state
try{
Object.keys(state).forEach(key => {
if(state[key] !== undefined) {
try{
state[key] = JSON.parse(getItem(key))
}catch(e){
state[key] = getItem(key)
}
}
})
} catch(e) {
console.error('初始化过程中获取持久化参数失败')
}
} else {
console.warn('getItem不是一个function,初始化时获取持久化内容的功能不可用')
}
observer(state, {
set: debounceStorage(state, setItem, setDelay)
})
}
/*
通用方法
*/
function getType(para) {
return Object.prototype.toString.call(para)
.replace(/\[object (.+?)\]/, '$1').toLowerCase()
}
const _state = {login:'',psw:''}
persistedState({
state:_state,
setItem: localStorage.setItem.bind(localStorage),
getItem: localStorage.getItem.bind(localStorage),
setDelay: 200
})
setTimeout(()=>{
_state.login={a:{b:[1,2,3]}}
console.log('重新指定值')
setTimeout(()=>{
_state.login.a.b.push(4)
console.log('push内容')
},3000)
},3000)
</script>
</body>
</html>