How to remove event listener in javascript?

I am wondering how can I remove an event listener after adding one of them, how do you use it in jquery?

document.removeEventListener('touchstart'); document.addEventListener('touchstart', function (e) { closePopupOnClick(e, popup); }); 

but this does not actually remove the event listener. If I add addEventListener code to the function and pass this function to removeEventListener, it will not work bc, you cannot pass parameters to the function. Does anyone know how to do this?

+8
source share
1 answer

Put the listener as a variable and attach it via .addEventListener

 var myListener = function (e) { closePopupOnClick(e, popup); }; document.addEventListener('touchstart', myListener, true); 

then pass it again when uninstalling with .removeEventListener

 document.removeEventListener('touchstart', myListener); 

If you are not in strict mode, you can force the listener to delete itself using arguments.callee

 document.addEventListener('touchstart', function (e) { closePopupOnClick(e, popup); document.removeEventListener('touchstart', arguments.callee); }, true); 

If you are in strict mode, you need to use the named function expression if you want the function to delete itself

 document.addEventListener('touchstart', function myListener(e) { closePopupOnClick(e, popup); document.removeEventListener('touchstart', myListener); }, true); 

If you want to use variables in the listener that can be changed by something (for example, a loop), then you can write a generator function, for example

 function listenerGenerator(popup) { return function (e) { closePopupOnClick(e, popup); }; } 

Now you can create a listener using listenerGenerator(popup) , and it will have the popup variable. Note that if popup is an object, it will be ByRef and therefore may still be subject to change.

+16
source

All Articles