admin管理员组

文章数量:1312895

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?

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?

Share Improve this question asked Feb 13, 2013 at 12:00 Nicolas Le Thierry d'EnnequinNicolas Le Thierry d'Ennequin 6,1645 gold badges39 silver badges57 bronze badges 2
  • can you provide your code whatever u have tried till now? – Neel Commented Feb 13, 2013 at 12:02
  • There's nothing very interesting with the code. 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. – Nicolas Le Thierry d'Ennequin Commented Feb 13, 2013 at 12:04
Add a ment  | 

2 Answers 2

Reset to default 11

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 remend avoiding this sort of thing, though. Instead, I'd remend 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 ment 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.)

try typeof() operator inside the if condition. if argument type es out to be same, you may try assigning a unique property both the passing objects/events in either case and then perform a check agains that property...

本文标签: javascriptjQuery determine if a function was called as a jQuery event handler (callback)Stack Overflow