For a while, my program ran smoothly with the line
canvas.addEventListener("click", funcName, false);
. However, I recently realized that at times I needed to replace this event listener with another one:
canvas.addEventListener("click", difFuncName, false);
.
To address this, I created four functions in my JavaScript files - two to add these event listeners and two to remove them.
What I observed was that when the function adding the new event listener calling difFuncName successfully added the listener and later executed the remover function without any issues. However, the initial event listener, which was now being called within a function, seemed to not work anymore.
Prior to moving the first listener inside its own function, my code only had a function containing:
canvas.removeEventListener("click", funcName,false);
, which also failed to remove the event listener as desired - resulting in both event listeners executing their respective functions.
To verify the execution of each function, I inserted console.log("checking"); into all four functions and confirmed that they were indeed being executed.
My question is why does one event listener operate perfectly fine when added and removed within a function, whereas the other struggles to be added or removed via a function.
Below are the snippets for the four functions:
function addEventListener(){
canvas.addEventListener("click", funcName ,false);
}
function removecanvasListener(){
canvas.removeEventListener("click", funcName,false);
}
function addUnitEventListener(){
canvas.addEventListener("click", difFuncName,false);
}
function removeUnitEventListener(){
canvas.removeEventListener("click", difFuncName,false);
}
In listenerFile.js:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var x1;
function funcName(event){
x1 = event.pageX;
console.log("doing something on click");
}
function difFuncName(event){
console.log("doing something else on click");
}
function addEventListener(){
canvas.addEventListener("click", funcName ,false);
}
function removecanvasListener(){
canvas.removeEventListener("click", funcName,false);
}
function addUnitEventListener(){
canvas.addEventListener("click", difFuncName,false);
}
function removeUnitEventListener(){
canvas.removeEventListener("click", difFuncName,false);
}
In changingEventListener.js:
function newListenerNeeded(){
removecanvasListener();
addUnitEventListener();
}
In ranafterListenerFile.js:
addEventListener();
ranafterListenerFile.js is actually loaded after listenerFile.js.