1 | const nanobus = require('nanobus');
|
2 |
|
3 | module.exports = class EventBus {
|
4 | constructor(log) {
|
5 | this.bus = nanobus();
|
6 | this.log = log;
|
7 |
|
8 | log.info('EventBus initialized');
|
9 | }
|
10 |
|
11 | handleDOMStorageChange({ key, newValue }) {
|
12 | if (key !== 'mocha-chrome-bus') {
|
13 | return;
|
14 | }
|
15 |
|
16 | let evnt;
|
17 |
|
18 | try {
|
19 | evnt = JSON.parse(newValue);
|
20 | } catch (e) {
|
21 | this.log.error('EventBus Error: Cannot Parse', newValue);
|
22 | throw e;
|
23 | }
|
24 |
|
25 | this.log.info('⇢ EventBus', evnt);
|
26 |
|
27 | this.bus.emit(evnt.name, evnt.data);
|
28 | }
|
29 |
|
30 | watch(DOMStorage) {
|
31 | DOMStorage.domStorageItemUpdated(this.handleDOMStorageChange.bind(this));
|
32 | DOMStorage.domStorageItemAdded(this.handleDOMStorageChange.bind(this));
|
33 | }
|
34 |
|
35 | emit(eventName, data) {
|
36 | this.bus.emit(eventName, data);
|
37 | }
|
38 |
|
39 | on(eventName, fn) {
|
40 | this.bus.on(eventName, fn);
|
41 | }
|
42 | };
|