I am trying to remove an event listener with parameters. I've understood that passing arguments when assigning a listener wouldn't work, so I finally worked a way to remove the arguments for the listener assignment. But it still not working.
I'm really not sure where to look next.
Here is the code (I have removed everything that has nothing to do with the issue)
let activeItemOnTheMove = false;
activeItem.addEventListener('click', e=>{
const defineOnMouseMove = () => { onMouseMove(activeItem) };
if(!activeItemOnTheMove){
document.addEventListener('mousemove', defineOnMouseMove);
activeItemOnTheMove = true;
}else{
document.removeEventListener('mousemove', defineOnMouseMove);
activeItemOnTheMove = false;
}
})
function onMouseMove(activeItem){
activeItem.style.position ='absolute';
activeItem.style.left = event.pageX + 'px';
activeItem.style.top = event.pageY + 'px';
activeItem.style.transform = 'translate(-50%,-50%)'
}
(I am using vanilla javascript)
I have read these answers, this is how I understood that I couldn't use an anonymous function. But I am not sure I understand the fundamental of why it doesn't work.
Juan Pablo Isaza
this is how I understood that I couldn't use an anonymous function
It doesn't matter whether the function is anonymous or not. What matters is using the same function with both addEventListener
and removeEventListener
. Your code isn't doing that, it's using a new function with removeEventListener
, which doesn't do anything because that function isn't registered as an event listener (it's just that a different function with the same code in it is).
Since you have to remember the function, you can use that variable as your flag as well if you like:
let activeMouseMoveHandler = null; // *** A variable to remember the function in
activeItem.addEventListener('click', e => {
if (!activeMouseMoveHandler) {
activeMouseMoveHandler = () => { onMouseMove(activeItem) };
document.addEventListener("mousemove", activeMouseMoveHandler);
} else {
document.removeEventListener("mousemove", activeMouseMoveHandler);
}
});