JQuery: determine if a function has been called as a jQuery event handler (callback)

I have a JavaScript function that can be called either directly or 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 type, but still Object).

Therefore, I need to be able to check (inside the function body) how this function was called in order to find out which argument it is dealing with.

Is there an easy way to do this?

+4
source share
2 answers

Take an argument, and then see if there is instanceof jQuery.Event :

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

Live example | A source

I would recommend avoiding this kind of thing. Instead, I would recommend that the event handler call the target function (instead of using the target function as the actual event handler) if you need to distinguish between behavior depending on how it was called.

From the comment to the question:

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

In this case, it is even simpler:

 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 need to pass null to a function, just call it without arguments. When you do this, e will be undefined , which is false. (The jQuery event object that passes the handler will never be false.)

+11
source

try the typeof () statement inside the if condition. if the type of the argument turns out to be the same, you can try to assign a unique property to passing objects / events anyway, and then check again that the property ...

-1
source

All Articles