开发者

How can I detect when a function is called as a jQuery callback vs. called directly?

I'm using hoverIntent which, as part of its settings, will call a function. I think this is called 'referencing a function' (correct?):

var HIconfig = {
     interval: 250,
     sensitivity: 8,
     over: myFunction,
     timeout: 100,
     out: myOtherFunction
};

However, I'd like to reuse said function at times and explicitly pass in a jQuery object. So, I added that to the function.

myFunction($myObject){
}

The challenge now is to figure out when the function is being referenced by hoverIntent or being explicitly called. My thought was that I'd check to see if $(this) contained a particular DOM element:

myFunction($myObject){
     if($(this).is('li')){
       $myObject = $(this)
     };

     $myObject.doSomething...

}

But...I'm having issues. If I log out both $(this) and $myObject these are the results:

Called via hoverIntent:

$(this) = [li#Trigger-0.nav-main-tab]
$myObject = Object { originalEvent=, more...}

Called via explicitely passing an object

$(this) = [Window PT02-home-page.php#]
$myObject = [li#Trigger-0.nav-main-tab]

I can test for $(this).is('li') in the first scenario, as it's true.

I can't in the second, though, as when I try to perform the test, Firefox doesn't like it:

g.nodeName is undefined

One suggestion was to switch to 1.4.1 and try to test fo开发者_JAVA技巧r the opposite via .isPlayObject:

if (jQuery.isPlainObject($myObject))...

This works just fine in Firefox. However, IE8 always returns true.

My questions:

  1. Is my logic simply way off in terms of how my function gets called from hoverIntent vs. directly?

  2. If not, is there a way to consistently test to see if I have explicitly passed in an object to my variable in the function?


I would do this totally differently. First, it's weird to have a function take a jQuery object as a parameter. Go the jQuery way and make your function into a jQuery plugin. For use in your hoverIntent configuration, you can either wrap your function in another little function, or do that with the new (1.4) jQuery.proxy() function.


Instead of passing an object, why not pass a simple boolean to indicate where it has been called from, for instance:

myFunction(asOption){
    if(asOption) {
        alert("called from hoverIntent");
    } else {
        alert("called from somewhere else");
    }
}

or am I completely missing the point?


You're making this unnecessarily complex. Just use a wrapper for the callback that passes the argument the function expects:

var HIconfig = {
     interval: 250,
     sensitivity: 8,
     // myFunction expects a jQuery object, so create one from the context
     over: function() { myFunction($(this)) },
     timeout: 100,
     out: myOtherFunction
};

...then you can skip the check inside your function altogether:

myFunction($myObject)
{
     $myObject.doSomething...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜