I've got an event handler in javascript that I'd like to overload :
function overloadedHandler(event, myObject){
if(event){
var elem = event.currentTarget;
} else {
var elem = myObject.x;
}
//function logic
}
$('.mydiv').on('click', overloadedHandler);
If I want to call the overloadedHandler
from another function (not as an event handler), what's the right way to do it ?
1. overloadedHandler(null, obj);
2. overloadedHandler(undefined, obj);
3. overloadedHandler(false, obj);
P.S. I understand that I could put //function logic
part in another function & call that when needed outside of an event handler, but I would like to know if there's anything wrong with the above approach?
Well indeed it seems a bit odd at first sight, but I would say that there is nothing wrong. It is basically equivalent to having an argument as optional, except that the event handling mechanism forces you to define the event as first argument so you cannot make it optional.
To make it as close as possible to an optional argument, I would set the event as undefined
when calling it not as an event handler, since this is what the value would be if it was an optional argument. null
would also be OK I guess, but I think false
is semantically wrong: you want to say that there is no event, not that the event is false.
One way to make it maybe even cleaner would call it with an event argument made for the purpose. In your example, that would be:
overloadedHandler({currentTarget: obj.x}, obj);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments