addEventListener firing multiple times for the same handle when passing in arguments with anonymous function

后端 未结 3 1522
迷失自我
迷失自我 2020-12-15 23:26

For some reason, the event listener is firing twice for each element when passing arguments into an anonymous function. I.e., the click event on element el will

相关标签:
3条回答
  • 2020-12-15 23:54

    The simplest solution is to create the new handler only once:

    var newHandle = function(event) { handle(event, myArgument); };
    
    el.addEventListener("click", newHandle, false);
    el.addEventListener("click", newHandle, false);
    
    0 讨论(0)
  • 2020-12-16 00:09

    Well,,

    el.addEventListener("click", handle, false);
    el.addEventListener("click", handle, false);
    

    Registers to the same function "handle()"

    el.addEventListener("click", function() { handle(event, myArgument); }, false);
    el.addEventListener("click", function() { handle(event, myArgument); }, false);
    

    Registers "function() { handle(event, myArgument)"... which are two unique anonymous functions. Thus it will fire twice.

    Although I don't fully understand why you would want to register it twice, the solution would be to create a function returning your function that takes parameters.

    el.addEventListener("click", crateHandle(myArgument), false);
    
    var createHandle = function(myArgument) {
      return function(event) {
        .... do something
      };
    }
    

    It still doesn't solve the fire twice issue though.

    0 讨论(0)
  • 2020-12-16 00:12

    addEventListener registers as many listeners as it is used.

    According to the documentation it takes 3 arguments, the third is useCapture which has nothing to do with registering listener twice or not. It is by default set to false, so adding false as a third parameter doesn't change much.

    0 讨论(0)
提交回复
热议问题