1 | function createBroadcast (initialState) {
|
2 | var listeners = {};
|
3 | var id = 1;
|
4 | var _state = initialState;
|
5 |
|
6 | function getState () {
|
7 | return _state
|
8 | }
|
9 |
|
10 | function setState (state) {
|
11 | _state = state;
|
12 | var keys = Object.keys(listeners);
|
13 | var i = 0;
|
14 | var 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 | var 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: getState, setState: setState, subscribe: subscribe, unsubscribe: unsubscribe }
|
38 | }
|
39 |
|
40 | export default createBroadcast;
|