Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: determine if a function was called as a jQuery event handler (callback)

I have a JavaScript function that can be called either directly, either as a callback from a jQuery event.

In the latter case, the jQuery Event object will be passed as an argument. When I call the function directly, I also provide an argument (of a different kind, but still an Object).

Therefore I need to be able to check (within the function body) how the function was invoked so as to know what sort of argument it's dealing with.

Is there a simple way to do that?

like image 216
Nicolas Le Thierry d'Ennequin Avatar asked Dec 27 '22 09:12

Nicolas Le Thierry d'Ennequin


1 Answers

Accept the argument and then see if it's instanceof jQuery.Event:

function yourFunction(e) {
    if (e instanceof jQuery.Event) {
        // ...it was an event handler call
    }
}

Live Example | Source

I would recommend avoiding this sort of thing, though. Instead, I'd recommend having the event handler call the target function (rather than using the target function as the actual event handler), if you need to distinguish the behavior depending on how it was called.

From your comment on the question:

What I tried simply is: when the function is called directly, I use a null value in first position and the useful argument in second position.

In that case, it's even easier:

function yourFunction(e) {
    if (e) {
        // ...it was an event handler call -- or at least,
        // a non-falsey argument of some kind was passed in
    }
}

You don't even have to pass null into the function, just call it with no arguments. When you do that, e will be undefined, which is falsey. (The event object jQuery passes the handler will never be falsey.)

like image 58
T.J. Crowder Avatar answered Jan 13 '23 18:01

T.J. Crowder