Hello all,
This is a follow-up question to a different question I asked not too long ago. Typically, you can access an event in a function call from a jQuery event like this:
$item.live("click", functionToCall);
and in the function:
function functionToCall(ev) {
// do something with ev here, like check 'ev.target'
}
But what if I wanted to send a parameter to functionToCall() and access the event? So something like this, maybe? :
$item.live("click", functionToCall($(this)); // send over parameter this time
and
function functionToCall(ev, $clickedItem) {
// both accessible here?
alert(ev.type);
alert($clickedItem.attr('id'));
}
Would that be acceptable, or is there a different way to send a parameter? Because this way doesn't seem right to me. Any help would be appreciated. Thanks.
CLARIFICATION: I realize that an anonymous callback function would allow me to access both, but for various reasons too lengthy to get into in this post, I need to use a function call rather than the anonymous function. So my question deals strictly with the scenario when an external function needs to be called. Thanks.
UPDATE: My original question presented the scenario of needing to pass $(this) as a parameter to the external function. As it turns out, $(this) will be accessible in the function without even needing to pass it, because of the way jQuery reassigns values to "this" based on events. So performing this code should work for my original question:
$item.live("click", functionToCall);
and
function functionToCall(ev) {
alert(ev.type);
alert($(this).attr('id')); // display id of item that was clicked
}
However, as others have answered, there is a different scenario that involves needing to pass a different kind of variable over as a parameter, such as a simply string or int. In this case, as others have notes, it becomes more complicated. But there do seem to be sufficient answers here to satisfy this second scenario (namely, "currying"). Thanks.