-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
executable file
·38 lines (33 loc) · 934 Bytes
/
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
export default function createBroadcast (initialState) {
let listeners = {}
let id = 1
let _state = initialState
function getState () {
return _state
}
function setState (state) {
_state = state
const keys = Object.keys(listeners)
let i = 0
const len = keys.length
for (; i < len; i++) {
// if a listener gets unsubscribed during setState we just skip it
if (listeners[keys[i]]) listeners[keys[i]](state)
}
}
// subscribe to changes and return the subscriptionId
function subscribe (listener) {
if (typeof listener !== 'function') {
throw new Error('listener must be a function.')
}
const currentId = id
listeners[currentId] = listener
id += 1
return currentId
}
// remove subscription by removing the listener function
function unsubscribe (id) {
delete listeners[id]
}
return { getState, setState, subscribe, unsubscribe }
}