UNPKG

934 BJavaScriptView Raw
1export 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 // if a listener gets unsubscribed during setState we just skip it
17 if (listeners[keys[i]]) listeners[keys[i]](state)
18 }
19 }
20
21 // subscribe to changes and return the subscriptionId
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 // remove subscription by removing the listener function
33 function unsubscribe (id) {
34 delete listeners[id]
35 }
36
37 return { getState, setState, subscribe, unsubscribe }
38}