1 | export default function createBroadcast (initialState) {
|
2 | let listeners = {}
|
3 | let id = 1
|
4 | let _state = initialState
|
5 |
|
6 | function getState () {
|
7 | return _state
|
8 | }
|
9 |
|
10 | function setState (state) {
|
11 | _state = state
|
12 | const keys = Object.keys(listeners)
|
13 | let i = 0
|
14 | const len = keys.length
|
15 | for (; i < len; i++) {
|
16 |
|
17 | if (listeners[keys[i]]) listeners[keys[i]](state)
|
18 | }
|
19 | }
|
20 |
|
21 |
|
22 | function subscribe (listener) {
|
23 | if (typeof listener !== 'function') {
|
24 | throw new Error('listener must be a function.')
|
25 | }
|
26 | const currentId = id
|
27 | listeners[currentId] = listener
|
28 | id += 1
|
29 | return currentId
|
30 | }
|
31 |
|
32 |
|
33 | function unsubscribe (id) {
|
34 | delete listeners[id]
|
35 | }
|
36 |
|
37 | return { getState, setState, subscribe, unsubscribe }
|
38 | }
|