Addeventlistener Firing Multiple Times For The Same Handle When Passing In Arguments With Anonymous Function
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 register once and,
Solution 1:
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);
Solution 2:
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) {
returnfunction(event) {
.... do something
};
}
It still doesn't solve the fire twice issue though.
Solution 3:
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.
Post a Comment for "Addeventlistener Firing Multiple Times For The Same Handle When Passing In Arguments With Anonymous Function"