how to pass a parameter to a event's handler?
here's what am trying to do, doesn't work:
for (var i = 0; i < myobj.length; i++) {
myobj[i].onmouseover = myfun(myobj[i]);
}
the following doesn't work neither.
myobj[i].onmouseover = myfun.call(myobj[i]);
myobj[i].onmouseover = function () {myfun(myobj[i]);};
myobj[i].onmouseover = function () {myfun.call(myobj[i]);};
Am primarily interested in why it doesn't work, and solution in the same style.
Thanks.
Using ES6 arrow functionWe can also pass additional parameters to event handlers. The problem with both above syntax is that a different callback instance is created each time the component is rendered, same as with the bind function.
In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the sayHello function. In our example, that argument is a string: 'James': ... return ( <button onClick={() => sayHello('James')}>Greet</button> ); ...
To set up an event listener you just need to have a variable that references an element and then call the addEventListener function on that element. This function takes a minimum of two parameters. The first parameter is just a string which is the name of the event to listen to.
Just use a creator function for your handlers to encapsulate the parameter to pass on.
function createHandler( param ) {
return function() {
myfun( param );
}
}
for (var i = 0; i < myobj.length; i++) {
myobj[i].onmouseover = createHandler( myobj[i] );
}
The reason your approach doesn't work is, because you don't pass on a function reference, but the result of a function call. So in your first example myfun( myobj[i] )
is evaluated and the result is passed on as the event handler.
I think, what you really mean is, that in case the event is fired, the function shall be evaluated. To do so you either have to pass the parameter via some global var or as a dataset property.
The cleaner solution, however, is to have a generator function as shown above.
Another approach is to use the fact that onmouseover
will be invoked as a method (not a function) on the DOM element which fires the event.
In other words, write your code as if you expected someone to do this:
obj = xahlees();
obj.onmouseover();
Here's a solution:
for (var i = 0; i < myobj.length; i++) {
myobj[i].onmouseover = function() { myFun(this) };
}
I've uploaded a more complete example .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With