Pitfalls of Remove EventListner in JS

·

1 min read

While addEventlistner function in Javascript gives us a lot of flexibility to deal with Events. So when we need to remove some event listener then we use removeEventlistener function, but there are some common pitfalls which we can be overlooked by us .

So here are some common pitfalls and their workarounds of removeEventlistner:

1) Removing an Anonymous event listener function.

Ex:


btn.addEventListener('click',()=>{alert("Hello");};

And if we try to remove above eventlistner by below code then it won't be removed :

 btn.removeEventListener('click',()=>{alert("Hello");};

The reason is because the Functios are refrence types in JS ,So here the functions defined in addEventListner and removeListner are diffrent.

We can overcome this situation by storing the refence of Event listner Function and then using that refrence to add and remove in the addEventListner and removeEventListner. Ex:

function Sayhello()
{
  alert("Hello there !");
}

btn.addEventListener('click',()=>{Sayhello();};

2 ) using bind method:

Since bind method also gives a newly created function so using bind will also not work here. Ex:

btn.addEventListner('click',sayHello.bind(this);)

If we try to remove above added event listner then it would not be removed as bind has given an new function to execute .