forked from alpinejs/alpine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (33 loc) · 1.08 KB
/
index.js
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
export default function (Alpine) {
let persist = () => {
let alias
let storage = localStorage
return Alpine.interceptor((initialValue, getter, setter, path, key) => {
let lookup = alias || `_x_${path}`
let initial = storageHas(lookup, storage)
? storageGet(lookup, storage)
: initialValue
setter(initial)
Alpine.effect(() => {
let value = getter()
storageSet(lookup, value, storage)
setter(value)
})
return initial
}, func => {
func.as = key => { alias = key; return func },
func.using = target => { storage = target; return func }
})
}
Alpine.$persist = persist()
Alpine.magic('persist', persist)
}
function storageHas(key, storage) {
return storage.getItem(key) !== null
}
function storageGet(key, storage) {
return JSON.parse(storage.getItem(key, storage))
}
function storageSet(key, value, storage) {
storage.setItem(key, JSON.stringify(value))
}