Add an event listener with sevral parameters and delete it later.

This seems to be a very popular question, although I did not seem to find any pertinat answers.

I am attaching an event, for example:

window.addEventListener('scroll', fnName, false); 

The problem is that fnName expects several parameters, so I tried

 window.addEventListener('scroll', (function( e ){ return fnName(e, some, param ) }()), false) 

but then window.removeEventListener no longer works, so I tried:

 window.removeEventListener('scroll', (function( e ){ return fnName(e, some, param ) }()), false) 
+1
source share
4 answers

Each time you declare an anonymous function, a new instance of the function is created. If you want to delete an existing function, you need to save a copy of the function instance.

 var temp = function () { fnName(e, some, param); }; window.addEventListener('scroll', temp, false); //elsewhere, window.removeEventListener('scroll', temp, false); 

It should also be noted that the use of

 (function (e){ return fnName(e, some, param) }()); 

calls fnName immediately with undefined as the first parameter. I doubt your intention.

+2
source

You have a self-initialization function:

 (function() { alert("a") })(); 

as you can warn this code about warnings "a" .

In your function, you then initialize fnName . What you need to do:

 window.addEventListener('scroll', function( event ) { fnName(event, some, param ); }, false); 

When the scroll event fnName , you then initialize fnName with your custom arguments.


And as indicated, if you want to remove the handler again, you will need a named function:

 function myFn( event ) { fnName(event, some, param ); } window.addEventListener('scroll', myFn, false); // Add event listener window.removeEventListener('scroll', myFn, false); // Remove event listener 
+1
source
 window.addEventListener('scroll', (function( e ){ return fnName(e, some, param ) }), false) 

just remove () to avoid direct execution after defining

0
source

As I am in the architecture of the AMD module, and I am trying to support an event handler as a private method, I just came up with this solution:

 define(function(){ var fnNmae = function( e ) { // i can now access fnName.param }; return { init : function() { fnName.param = { one : 1, two : 2 } window.addEventListener('scroll', fnName, false); } }) 
0
source

Source: https://habr.com/ru/post/1442404/


All Articles