Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how is to remove the EventListener?

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 );

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading