I'm trying to have a general function that allows to subscribe to any event. I want make sure that is only made one subscription for each event and element. So, before I add a new event listener, I remove the previous one.
The problem is, the way that I'm making it the previous event is not being remove and I don't know why.
Follows a working example:
function delegate(el, evt, sel, handler) {
let eventListenerHandler = (event) => {
var t = event.target;
while (t && t !== this) {
if (t.matches && t.matches(sel)) {
handler.call(t, event);
}
t = t.parentNode;
}
}
el.removeEventListener(evt, eventListenerHandler, evt === "focus" ? true : false);
el.addEventListener(evt, eventListenerHandler, evt === "focus" ? true : false);
}
let consoleLog = () => console.log("WAS FOCUS");
delegate(document, "focus", "input", consoleLog);
delegate(document, "focus", "input", consoleLog);
<input/>
<input/>
As you can see in the example, each time an input is selected, is printing 2 times the message "WAS FOCUS" and want I want is to make sure that only one is printed.
Thank you in advance.
eventListenerHandlers across calls are two different function objects. You need to use the same one, or hold on separately to the existing one if the functions might be different.