LP#1086458: add class to manage event listeners
authorGalen Charlton <gmc@esilibrary.com>
Thu, 24 Jan 2013 16:56:30 +0000 (11:56 -0500)
committerBen Shum <bshum@biblio.org>
Mon, 4 Mar 2013 19:49:33 +0000 (14:49 -0500)
EventListenerList allows one to maintain a list
of event listeners, then remove them all when it's
time to clean up a window.

Usage is:

var list = new EventListenerList();
// attach an event listener
list.add(node, 'command', function(ev) { alert('BOO!'); }, false);
...
// get rid of them
list.removeAll();

Based on an idea by Jason Etheridge.

Signed-off-by: Galen Charlton <gmc@esilibrary.com>
Signed-off-by: Ben Shum <bshum@biblio.org>
Open-ILS/xul/staff_client/chrome/content/OpenILS/global_util.js

index 09c8671..615108f 100644 (file)
@@ -2,6 +2,43 @@
         xulG = window.arguments[0];
     }
 
+    function EventListenerList() {
+        this._listeners = [];
+        return this;
+    }
+
+    EventListenerList.prototype = {
+        'add' : function(node, type, listener, useCapture) {
+            try {
+                node.addEventListener(type,listener,useCapture);
+                this._listeners.push({
+                    'node' : node,
+                    'type' : type,
+                    'listener' : listener,
+                    'useCapture' : useCapture
+                });
+            } catch(E) {
+                alert(location.href + ' Error adding event listener ' + type + ': ' + E);
+            }
+        },
+
+        'removeAll' : function() {
+            try {
+                if (typeof this._listeners != 'undefined') {
+                    for (var i = 0; i < this._listeners.length; i++) {
+                        this._listeners[i].node.removeEventListener(
+                            this._listeners[i].type,
+                            this._listeners[i].listener,
+                            this._listeners[i].useCapture
+                        );
+                    }
+                }
+            } catch(E) {
+                alert(location.href + ' Error in unloadEventListeners(): ' + E);
+            }
+        }
+    }
+
     function $(id) { return document.getElementById(id); }
 
     function oils_unsaved_data_V() {