Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  65] [ 4]  / answers: 1 / hits: 19298  / 8 Years ago, tue, april 26, 2016, 12:00:00

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

More From » jquery

 Answers
30

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>




[#62397] Saturday, April 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;