Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a parameter to a event's handler

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.

like image 921
Xah Lee Avatar asked Apr 25 '12 12:04

Xah Lee


People also ask

Is it possible to pass an additional parameter to an event handler?

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.

How do you pass parameters on onClick react?

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> ); ...

How do you add an event listener to a variable?

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.


2 Answers

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.

like image 166
Sirko Avatar answered Oct 10 '22 10:10

Sirko


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 .

like image 39
Leonel Avatar answered Oct 10 '22 11:10

Leonel