1 | const RemoteInterface = require("./remote-interface.js");
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | class GlobalEventHandler {
|
8 | constructor() {
|
9 | this._eventListeners = {};
|
10 |
|
11 |
|
12 |
|
13 | window.addEventListener("message", (evt) => {
|
14 | const data = evt.data;
|
15 | let jsonData = undefined;
|
16 |
|
17 | try {
|
18 | jsonData = JSON.parse(data);
|
19 | }
|
20 | catch (e) {
|
21 |
|
22 |
|
23 | jsonData = undefined;
|
24 | }
|
25 |
|
26 |
|
27 | if (jsonData && jsonData.event && jsonData.data) {
|
28 |
|
29 | if (this._eventListeners[jsonData.event]) {
|
30 | const remoteInterface = new RemoteInterface(evt.source, evt.origin);
|
31 |
|
32 |
|
33 | this._eventListeners[jsonData.event].forEach((callback) => {
|
34 | try {
|
35 | callback(remoteInterface, jsonData.data);
|
36 | }
|
37 | catch (e) {
|
38 | console.error("GlobalEventHandler.message() error occured during callback ");
|
39 | console.error(e);
|
40 | }
|
41 | });
|
42 | }
|
43 | }
|
44 | });
|
45 | }
|
46 |
|
47 | listen(event, callback) {
|
48 | if (typeof callback !== "function") {
|
49 | throw new TypeError("GlobalEventHandler.listen(event, callback) callback must be a type of function.");
|
50 | }
|
51 |
|
52 | if (!this._eventListeners[event]) {
|
53 | this._eventListeners[event] = [];
|
54 | }
|
55 |
|
56 | this._eventListeners[event].push(callback);
|
57 | }
|
58 | }
|
59 |
|
60 | GlobalEventHandler.instance = () => {
|
61 | if (!GlobalEventHandler._default) {
|
62 | GlobalEventHandler._default = new GlobalEventHandler();
|
63 | }
|
64 |
|
65 | return GlobalEventHandler._default;
|
66 | };
|
67 |
|
68 | module.exports = GlobalEventHandler; |
\ | No newline at end of file |