Frank_G
Frank_G

Reputation: 53

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

Upvotes: 2

Views: 69

Answers (1)

Vinod Liyanage
Vinod Liyanage

Reputation: 1155

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

Upvotes: 1

Related Questions