Question

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?

Was it helpful?

Solution

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

OTHER TIPS

In javascript, null, undefined, and false are all falsey, therefore event in if (event) will evaluate as false anytime those values are passed into that function via that parameter. There is nothing wrong with it any way you do it since it's simple evaluation. Unless you want to do different things with null, undefined, or false in the function (or there are extenuating circumstances like specific conventions, 'use strict' usages, etc), it doesn't matter much.

You can reuse the following function just by setting first argument that something is false, as you pointed you can use any of those.

overloadedHandler(null, obj);
overloadedHandler(undefined, obj);
overloadedHandler(false, obj);

All of them would be fine. But I would use 'null', although it's subjective opinion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top