Well, I use addEventListener and I cannot (or at least don't know how) pass arguments to the function.
Let's say we have a function:
function warning(arg1, arg2) {alert('Argument 1: ' + arg1 + ', Argument2: ' + arg2 + '.');}
It's possible to have:
onclick="warning('my argument 1', 'my argument 1');" as an html attribut.
But I think it's not posible to do it like this (still the same function):
el.addEventListener("click", warning('my argument 1', 'my argument 1'), false);
So how can I pass arguments to the function?
addEventListener requires a reference to a function. By passing arguments, you are inserting the return value of the function. An equivalent of what you want:
document.addEventListener('eventname', function(event) { doSomething('arg1', 'arg2') }, false);
Cool, just what I need.
Thanx!
Now that I've used
document.addEventListener("mousemove", function(event) {move (objectID)}, false);
now I cannot removeEventListener . I've tried many things:
------------------------------------------------------------------------------------
document.removeEventListener("mousemove", function(event) {move (objectID)}, false);
document.removeEventListener("mousemove", move, false);
...
------------------------------------------------------------------------------------
But none of them worked. How can I fix this?
I've written a short page just for this example. Please check it out.
page (http://www2.arnes.si/~rcarl/test_addEventListener.html)
removeEventListener requires the identical arguments passed to addEvent Listener.
You are using an anonymous function as the second argument, which is forever lost once used:
function(){doSomething()} == function(){doSomething()}
// false
Which means you'll have to declare your wrapper function separate:
function eventWrapper(event) {
move(objectID);
}
And pass eventWrapper into addEventListener as opposed to function(event) {move (objectID)}
Well, I still have to pass an argument to a function using addEventListener.
But I've solved my problem using one simple ****** variable :).
But thnx anyway!
Bonker
07-13-2005, 12:36 PM
Hi Rok
Can you post your solution ? I have the same problem.
Thanx
Royal2000H
06-02-2007, 11:46 PM
I'm having the same issue....
does someone have a solution because
I need removeEventListener to work as well as passing variables
(sorry to bring up such an old topic)
jkd's post explained it pretty well. If you have something that looks like:
element.addEventListener('click',function() { foo(id);},false);
then you need to use:
element.addEventList('click',bar=function() { foo(id);},false);
//and then
element.removeEventListener('click',bar,false);
[/code]