UNPKG

2.25 kBJavaScriptView Raw
1const RemoteInterface = require("./remote-interface.js");
2
3/**
4 * This is a singleton class that handles events on a global basis. Allows
5 * registering local event listeners etc..
6 */
7class GlobalEventHandler {
8 constructor() {
9 this._eventListeners = {};
10
11 // global handler that forwards events to their respectful places
12 // throughout the framework
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 // catch does nothing
22 // this event might not be what we are looking for
23 jsonData = undefined;
24 }
25
26 // make sure the event is properly formatted
27 if (jsonData && jsonData.event && jsonData.data) {
28 // see if there are any listeners for this
29 if (this._eventListeners[jsonData.event]) {
30 const remoteInterface = new RemoteInterface(evt.source, evt.origin);
31
32 // loop through and call all the event handlers
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
60GlobalEventHandler.instance = () => {
61 if (!GlobalEventHandler._default) {
62 GlobalEventHandler._default = new GlobalEventHandler();
63 }
64
65 return GlobalEventHandler._default;
66};
67
68module.exports = GlobalEventHandler;
\No newline at end of file