Dreams
Dreams

Reputation: 8506

How to remove event listener?

Below is my code for event listener

window.addEventListener("beforeunload", function (e) {
        if(sessionStorage.token != "abide" )  {
          // call api
        }
});

What if I want to remove this event listener, what should I do?

Is the code working like below??

window.removeEventListener("before unload");

Upvotes: 12

Views: 23715

Answers (1)

The Process
The Process

Reputation: 5953

To remove event listener, your event handler function has to be an external named function, not anonymous (you need a reference to that function):

window.addEventListener("beforeunload", functionToRun);

function functionToRun(e){
     if(sessionStorage.token != "abide" ){
        // call api
     }
}
window.removeEventListener("beforeunload",functionToRun);


Alternative : You can also remove it inside the anonymous function call using arguments.callee which is referencing that anonymous function.
ex:

var button=document.getElementById('button');

button.addEventListener('click',function(e){

   //some code to be runned       
  this.removeEventListener('click', arguments.callee);

});

Note: your event handler function has to be fired once, in order to remove it in the above way.

var button = document.getElementById('button');

button.addEventListener('click', function(e) {

  alert('clicked');

  this.removeEventListener('click', arguments.callee);
});
<button id="button">click</button>

Upvotes: 30

Related Questions