How to pass a parameter to a event’s handler?
Here’s what am trying to do, but it 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.
Just use a creator function for your handlers to encapsulate the parameter to pass on.
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.