Javascript eventhandler: issue with executing handler that received parameters

I had this problem:

I have defined an event handler that requires parameters from it.

var handler = function(p1, p2){
    //some code
}

Then I add an event handler to the object inside the function.

function foo(p1, p2){
    //Some code
    obj.addEventListener('click', handler(p1, p2), false)
}

As you already know, the above code is incorrect. He will not listen to this event. Instead, it will perform the function instantly. Now, to fix this, I can just erase handler(p1, p2)and paste function(){ handler(p1, p2) }. But the problem is that I have another function that I want to remove the event listener, which is not possible in the last solution.

function koo(){
    //Some code
    obj.removeEventListener('click', handler, false)
}

How to fix it?

+3
source share
3 answers

I think you need to create a closure:

var createHandler = function(p1, p2){
    return function (event) {
        //some code that uses p1 and p2
    };
};

var handler;

... , p1 p2:

function foo(p1, p2){
    handler = createHandler(p1, p2);
    //Some code
    obj.addEventListener('click', handler, false);
}

function koo(){
    //Some code
    obj.removeEventListener('click', handler, false);
    handler = null;
}

, handler .


. , , createHandler foo :

var handler; // we need this to be accessible both to foo and koo

function foo(p1, p2){
    handler = function(event) {
        // some code that uses p1 and p2
    };
    //Some code
    obj.addEventListener('click', handler, false);
}

function koo(){
    //Some code
    obj.removeEventListener('click', handler, false);
    handler = null;
}
+2

, , , , .

...

(function() {

   var p1 = 'a',
       p2 = 'b',
       obj = document.getElementById('my-object');

   var handleClick = function(event) {
      // Access to p1 and p2
      // Access to `event` object containing info about the event
   }

   obj.addEventListener('click', handleClick, false);

   // If you want to remove it
   obj.removeEventListener('click', handleClick, false);

})();

, ? ?

+2

Isn't it like this:

function foo(){
    //Some code
    obj.addEventListener('click', handler, false)
}

Pass a function instead of a call.

+1
source

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


All Articles