-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
51 lines (40 loc) · 1.07 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
45
46
47
48
49
50
51
const { getContext, setContext } = require('svelte')
const STORE = typeof Symbol !== 'undefined' ? Symbol('storeon') : '@@storeon'
function provideStoreon (store) {
setContext(STORE, store)
}
function useStoreon (...keys) {
let store = getContext(STORE)
if (process.env.NODE_ENV !== 'production' && !store) {
throw new Error(
'Could not find storeon context value.' +
'Please ensure you provide store using "provideStoreon" function'
)
}
let subscribers = {}
let makeSubscribable = key => {
let subscribe = run => {
let state = store.get()
subscribers[key] = run
run(state[key])
return () => {
delete subscribers[key]
}
}
return { subscribe }
}
store.on('@changed', (_, changed) => {
keys.forEach(key => {
if (key in changed && subscribers[key]) {
subscribers[key](changed[key])
}
})
})
let data = {}
keys.forEach(key => {
data[key] = makeSubscribable(key)
})
data.dispatch = store.dispatch
return data
}
module.exports = { provideStoreon, useStoreon }