2

How can I remove the EventListener? Attached is a quick example of where it doesn't work. How should it be correct?

function test_function(a='', b='') {    
    console.log('test_function started. a='+a+', b='+b);    
}

document.body.addEventListener('mousemove', ()=>{   test_function('testa', 'testb');    });
document.body.removeEventListener("mousemove", test_function );
Frank_G
  • 53
  • 4
  • 4
    You have attached an anonymous function to the event, not `test_function`. – Teemu Aug 24 '22 at 10:02
  • 1
    You need to keep a reference to the anonymous function: https://stackoverflow.com/questions/4950115/removeeventlistener-on-anonymous-functions-in-javascript – DanieleAlessandra Aug 24 '22 at 10:02
  • for further reference to the docs https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener _"Given an event listener previously added by calling addEventListener(), you may eventually come to a point at which you need to remove it. Obviously, you need to specify the same type and listener parameters to removeEventListener()."_ – Diego D Aug 24 '22 at 10:04

1 Answers1

1

test_function is not the event listener function of the event handler. it is
()=>{ test_function('testa', 'testb') this whole anonymous function.

In this document.body.removeEventListener("mousemove", test_function ); you are passing reference of test_function to removeEventListener. but the actual function is ()=>{ test_function('testa', 'testb')

In order to use removeEventListener, you can refactor code this way.

function test_function(a='', b='') {    
    console.log('test_function started. a='+a+', b='+b);    
}

const handleMouseMove = () => test_function('testa', 'testb');

document.body.addEventListener('mousemove', handleMouseMove);
document.body.removeEventListener("mousemove", handleMouseMove);

checkout mdn documentation,

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

Vinod Liyanage
  • 945
  • 4
  • 13
  • And how can I add the event in a single line? That would be clearer in my case. – Frank_G Aug 24 '22 at 10:29
  • the point is that you need to pass the same event handler function reference for both addEventListener and removeEventListener. hope you understand! – Vinod Liyanage Aug 24 '22 at 10:33
  • @Frank_G, do you want to remove event listener after it gets executed once? – Ashish Patil Aug 24 '22 at 10:38
  • I want to add an event with dynamical parameters. And on other place I want to remove the event. If I could make setting and removing the event in one line of code each, that would be clearer. – Frank_G Aug 24 '22 at 10:45