How can I determine when a function is being called as a jQuery callback versus a direct call?

I use hoverIntent, which, as part of its settings, will call a function. I think this is called a "function reference" (right?):

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

However, I would like to reuse the specified function at times and explicitly pass the jQuery object. So, I added this to the function.

 myFunction($myObject){ } 

The challenge now is to find out when the function refers to hoverIntent or is explicitly called. I thought I would check if $ (this) would contain a specific DOM element:

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

But ... I have a problem. If I exit both $ (this) and $ myObject, these will be the following results:

Called via hoverIntent:

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

Called by direct object transfer

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

I can check $(this).is('li') in the first script, as that is true.

I cannot in the second, although when I try to run the test, Firefox does not like it:

 g.nodeName is undefined 

One suggestion was to switch to 1.4.1 and try to check the opposite via .isPlayObject:

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

This works great in Firefox. However, IE8 always returns true.

My questions:

  • Is my logic just remote in terms of how my function is called from hoverIntent or directly?

  • If not, is there a way to test sequentially so that I explicitly pass the object to my variable in this function?

+4
source share
3 answers

I would do it completely differently. First, it is strange to have a function that takes a jQuery object as a parameter. Follow the jQuery path and turn your function into a jQuery plugin. To use hoverIntent in your configuration, you can either wrap your function in another small function, or do it with the new function (1.4) jQuery.proxy ().

+3
source

Instead of passing an object, why not pass a simple boolean value to indicate where it was called from, for example:

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

or am I not completely losing the point?

+1
source

You make it unnecessarily complicated. Just use a wrapper for the callback that passes the argument that 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 generally skip checking inside your function:

 myFunction($myObject) { $myObject.doSomething... } 
+1
source

Source: https://habr.com/ru/post/1300550/


All Articles