Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
like image 786
Dreams Avatar asked Apr 26 '16 13:04

Dreams


1 Answers

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>
like image 50
The Process Avatar answered Nov 16 '22 21:11

The Process