I am using object oriented Javascript in conjunction with registering event listeners. From what I understand about event listeners, if the function applied to the eventtarget is already registered, repeated attempts to add the same event listener will be ignored. In other words, it should fire only once. But this is not the case in the code below (can also be seen on jsfiddle).
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
Multiple event listeners
If multiple identical EventListeners are registered on the same EventTarget with the same parameters, duplicate instances will be discarded. They do not call the EventListener twice, and since duplicates are discarded, they do not need to be manually removed using the removeEventListener method.
http://jsfiddle.net/qd1e8f6c/
HTML
<div id="wrapper">
<input id="t1" type="text" />
<input id="btn" type="button" />
</div>
Js
var namespace = namespace || {};
namespace.event = {
addListener: function(el, type) {
var handle = function() {
switch (type) {
case "focus":
console.log(el.value);
break;
case "click":
console.log(el.id + " was clicked");
break;
}
};
el.addEventListener(type, handle, false);
}
};
namespace.ExampleClass = function() {
this.init = function(el1, el2) {
el1.value = "123";
el2.value = "Click Me";
};
};
var textbox = document.getElementById("t1");
var button = document.getElementById("btn");
var inst = new namespace.ExampleClass();
inst.init( textbox, button );
namespace.event.addListener(textbox, "focus");
namespace.event.addListener(button, "click");
namespace.event.addListener(textbox, "focus");
namespace.event.addListener(button, "click");
As you can see in the last few lines of the above code, a function with a name addListeneris executed twice, which logs an event for each input. Then addListenerexecuted again. I expect it to not be registered again and ignored, but it really is registered. I do not understand. The function in the namespace, called handle, is exactly the same. What am I doing wrong here?
Any help would be great. Thank you very much.