I am teaching myself JavaScript and came across a situation where if I call an event listener on both the capture and bubble phases, removing that listener does not work.
function clickHandler(e, objId, num) {
var obj = document.getElementById(objId);
obj.innerHTML = "DIV " + num + " says " + " at X position: " + e.screenX;
}
function wrapperOne(e) {
clickHandler(e, "heading", 1);
e.target.removeEventListener('click', wrapperOne);
}
function wrapperTwo(e) {
clickHandler(e, "heading", 2);
e.target.removeEventListener('click', wrapperTwo);
}
function onloadHandler() {
document.getElementById("div1").addEventListener('click', wrapperOne, true);
document.getElementById("div2").addEventListener('click', wrapperTwo, true);
}
With this code I can continue to call wrapperOne
and wrapperTwo
even after the removeEventListener
function has been called. If I pass false
in the addEventListener
in onloadHandler
then the event handler does get removed. Could someone explain these two different behaviors?
Use e.target.removeEventListener('click', wrapperOne, true);
The third parameter of addEventListener
and removeEventListener
is the useCapture
parameter. To be cross-browser supported, you have to specify that boolean on both addEventListener
and removeEventListener
Reason why removeEventListener
worked when you used false
in addEventListener
is because false
is the default value for the useCapture
parameter.
If you attached an event in the "capture" phase, then you have to tell it to remove the event from the "capture" phase.
See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener for more information.