RemoveEventListener for Anonymous Functions in JavaScript

I have an object in which there are methods. These methods are placed in an object inside an anonymous function. It looks like this:

var t = {}; window.document.addEventListener("keydown", function(e) { t.scroll = function(x, y) { window.scrollBy(x, y); }; t.scrollTo = function(x, y) { window.scrollTo(x, y); }; }); 

(there is much more code, but this is enough to show the problem)

Now I want to stop the event listener in some cases. Therefore, I am trying to do removeEventListener, but I cannot figure out how to do this. I read in other questions that it is not possible to call removeEventListener for anonymous functions, but is this the case in this situation?

I have a method in t created inside an anonymous function, and so I thought it was possible. It looks like this:

 t.disable = function() { window.document.removeEventListener("keydown", this, false); } 

Why can't I do this?

Is there any other (good) way to do this?

Information about the bonus; this should only work in Safari, therefore there is no IE support.

+85
javascript safari javascript-events anonymous-function dom-events
Feb 09 2018-11-11T00:
source share
12 answers

I believe that this is the point of an anonymous function, it lacks a name or a way to refer to it.

If I were you, I would just create a named function or put it in a variable, so you have a link to it.

 var t = {}; var handler = function(e) { t.scroll = function(x, y) { window.scrollBy(x, y); }; t.scrollTo = function(x, y) { window.scrollTo(x, y); }; }; window.document.addEventListener("keydown", handler); 

Then you can delete it with

 window.document.removeEventListener("keydown", handler); 
+64
Feb 09 '11 at 21:41
source share

if you are inside the actual function, you can use arguments.callee as a reference to the function. how in:

 button.addEventListener('click', function() { ///this will execute only once alert('only once!'); this.removeEventListener('click', arguments.callee); }); 

EDIT: This will not work if you are working in strict mode ( "use strict"; )

+92
Jul 16 '12 at 20:23
source share

Otto Nascarella strict version:

 button.addEventListener('click', function handler() { ///this will execute only once alert('only once!'); this.removeEventListener('click', handler); }); 
+38
Dec 27 '16 at 10:33
source share
 window.document.removeEventListener("keydown", getEventListeners(window.document.keydown[0].listener)); 

There may be several anonymous functions, keydown 1

Warning: only works in Chrome Dev Tools and cannot be used in code : link

+9
Apr 10 '15 at 12:24
source share

Not an anonymous option

 element.funky = function() { console.log("Click!"); }; element.funky.type = "click"; element.funky.capt = false; element.addEventListener(element.funky.type, element.funky, element.funky.capt); // blah blah blah element.removeEventListener(element.funky.type, element.funky, element.funky.capt); 

After receiving feedback from Andy (quite correctly, but, like in many examples, I wanted to show a context extension of the idea), here was a less complicated presentation:

 <script id="konami" type="text/javascript" async> var konami = { ptrn: "38,38,40,40,37,39,37,39,66,65", kl: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] }; document.body.addEventListener( "keyup", function knm ( evt ) { konami.kl = konami.kl.slice( -9 ); konami.kl.push( evt.keyCode ); if ( konami.ptrn === konami.kl.join() ) { evt.target.removeEventListener( "keyup", knm, false ); /* Although at this point we wish to remove a listener we could easily have had multiple "keyup" listeners each triggering different functions, so we MUST say which function we no longer wish to trigger rather than which listener we wish to remove. Normal scoping will apply to where we can mention this function and thus, where we can remove the listener set to trigger it. */ document.body.classList.add( "konami" ); } }, false ); document.body.removeChild( document.getElementById( "konami" ) ); </script> 

This allows for an efficiently anonymous functional structure, avoids the use of a virtually laid-back caller, and makes it easy to delete.

By the way:: removing the script element immediately after installing the listener is a nice trick to hide the code, which, perhaps, would not be completely obvious to prying eyes (spoils the surprise;)

So the method is (simpler):

 element.addEventListener( action, function name () { doSomething(); element.removeEventListener( action, name, capture ); }, capture ); 
+2
Jan 01 '13 at 3:55
source share

This is not ideal, as it removes everything, but may work for your needs:

 z = document.querySelector('video'); z.parentNode.replaceChild(z.cloneNode(1), z); 

Cloning a node copies all its attributes and their values, including built-in (built-in) listeners. It does not copy event listeners using addEventListener ()

Node.cloneNode ()

+2
Dec 12 '15 at 10:12
source share

in modern browsers you can do the following ...

 button.addEventListener( 'click', () => { alert( 'only once!' ); }, { once: true } ); 

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters

+2
Nov 23 '18 at 9:49
source share

JavaScript : addEventListener method registers the specified listener in the EventTarget (Element | document | Window) that it called.

EventTarget. addEventListener ( event_type , handler_function, Bubbling | Capturing );

Mouse, keyboard events Test example in WebConsole:

 var keyboard = function(e) { console.log('Key_Down Code : ' + e.keyCode); }; var mouseSimple = function(e) { var element = e.srcElement || e.target; var tagName = element.tagName || element.relatedTarget; console.log('Mouse Over TagName : ' + tagName); }; var mouseComplex = function(e) { console.log('Mouse Click Code : ' + e.button); } window.document.addEventListener('keydown', keyboard, false); window.document.addEventListener('mouseover', mouseSimple, false); window.document.addEventListener('click', mouseComplex, false); 

The removeEventListener method removes the event listener previously registered with EventTarget.addEventListener ().

 window.document.removeEventListener('keydown', keyboard, false); window.document.removeEventListener('mouseover', mouseSimple, false); window.document.removeEventListener('click', mouseComplex, false); 

caniuse

+1
Jan 12 '16 at 2:35
source share

To give a more modern approach to this:

 //one-time fire element.addEventListener('mousedown', { handleEvent: function (evt) { element.removeEventListener(evt.type, this, false); } }, false); 
+1
Sep 01 '16 at 19:09
source share

Perhaps not the best solution in terms of what you ask. I still have not defined an efficient method to remove an anonymous function declared inline with an event listener call.

I personally use the variable to store the <target> and declare the function outside the event handler call, for example:

const target = document.querySelector('<identifier>');

function myFunc(event) { function code; }

target.addEventListener('click', myFunc);

Then remove the listener:

target.removeEventListener('click', myFunc);

Not the best recommendation you will get, but to remove anonymous functions, the only solution I found useful is to remove and then replace the HTML element. I'm sure there should be a better vanilla JS method, but I haven't seen it yet.

0
Jan 02
source share

I came across the same problem and this was the best solution I could get:

 /*Adding the event listener (the 'mousemove' event, in this specific case)*/ element.onmousemove = function(event) { /*do your stuff*/ }; /*Removing the event listener*/ element.onmousemove = null; 

Please keep in mind that I checked this only for the window element and for the 'mousemove' event, so there might be some problems with this approach.

0
Jul 11 '18 at 21:57
source share
 window.document.onkeydown = function(){}; 
-four
Nov 28 '13 at 23:54
source share



All Articles