summaryrefslogtreecommitdiff
path: root/platform/javascript/js/libs/library_godot_os.js
diff options
context:
space:
mode:
authorFabio Alessandrelli <fabio.alessandrelli@gmail.com>2021-09-12 13:40:07 +0200
committerFabio Alessandrelli <fabio.alessandrelli@gmail.com>2021-10-05 14:15:07 +0200
commit68616edcbc4aebd34ee98b78b1d165190fdcb9a6 (patch)
treeb4b2868996ff1b471a87ee6c6438f8be87da8bae /platform/javascript/js/libs/library_godot_os.js
parentc494e442bcc1fab9b31c0031c517ac1375ab1625 (diff)
[HTML5] Refactor JS library listeners to OS.
Diffstat (limited to 'platform/javascript/js/libs/library_godot_os.js')
-rw-r--r--platform/javascript/js/libs/library_godot_os.js40
1 files changed, 40 insertions, 0 deletions
diff --git a/platform/javascript/js/libs/library_godot_os.js b/platform/javascript/js/libs/library_godot_os.js
index 99e7ee8b5f..c552e99415 100644
--- a/platform/javascript/js/libs/library_godot_os.js
+++ b/platform/javascript/js/libs/library_godot_os.js
@@ -328,3 +328,43 @@ const GodotOS = {
autoAddDeps(GodotOS, '$GodotOS');
mergeInto(LibraryManager.library, GodotOS);
+
+/*
+ * Godot event listeners.
+ * Keeps track of registered event listeners so it can remove them on shutdown.
+ */
+const GodotEventListeners = {
+ $GodotEventListeners__deps: ['$GodotOS'],
+ $GodotEventListeners__postset: 'GodotOS.atexit(function(resolve, reject) { GodotEventListeners.clear(); resolve(); });',
+ $GodotEventListeners: {
+ handlers: [],
+
+ has: function (target, event, method, capture) {
+ return GodotEventListeners.handlers.findIndex(function (e) {
+ return e.target === target && e.event === event && e.method === method && e.capture === capture;
+ }) !== -1;
+ },
+
+ add: function (target, event, method, capture) {
+ if (GodotEventListeners.has(target, event, method, capture)) {
+ return;
+ }
+ function Handler(p_target, p_event, p_method, p_capture) {
+ this.target = p_target;
+ this.event = p_event;
+ this.method = p_method;
+ this.capture = p_capture;
+ }
+ GodotEventListeners.handlers.push(new Handler(target, event, method, capture));
+ target.addEventListener(event, method, capture);
+ },
+
+ clear: function () {
+ GodotEventListeners.handlers.forEach(function (h) {
+ h.target.removeEventListener(h.event, h.method, h.capture);
+ });
+ GodotEventListeners.handlers.length = 0;
+ },
+ },
+};
+mergeInto(LibraryManager.library, GodotEventListeners);