1 | (function (global, factory) {
|
2 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
|
3 | typeof define === 'function' && define.amd ? define(factory) :
|
4 | (global.brcast = factory());
|
5 | }(this, (function () {
|
6 |
|
7 | function createBroadcast (initialState) {
|
8 | var listeners = {};
|
9 | var id = 1;
|
10 | var _state = initialState;
|
11 |
|
12 | function getState () {
|
13 | return _state
|
14 | }
|
15 |
|
16 | function setState (state) {
|
17 | _state = state;
|
18 | var keys = Object.keys(listeners);
|
19 | var i = 0;
|
20 | var len = keys.length;
|
21 | for (; i < len; i++) {
|
22 |
|
23 | if (listeners[keys[i]]) { listeners[keys[i]](state); }
|
24 | }
|
25 | }
|
26 |
|
27 |
|
28 | function subscribe (listener) {
|
29 | if (typeof listener !== 'function') {
|
30 | throw new Error('listener must be a function.')
|
31 | }
|
32 | var currentId = id;
|
33 | listeners[currentId] = listener;
|
34 | id += 1;
|
35 | return currentId
|
36 | }
|
37 |
|
38 |
|
39 | function unsubscribe (id) {
|
40 | delete listeners[id];
|
41 | }
|
42 |
|
43 | return { getState: getState, setState: setState, subscribe: subscribe, unsubscribe: unsubscribe }
|
44 | }
|
45 |
|
46 | return createBroadcast;
|
47 |
|
48 | })));
|