代码之家  ›  专栏  ›  技术社区  ›  DA.

如何检测函数作为jquery回调调用与直接调用的时间?

  •  4
  • DA.  · 技术社区  · 16 年前

    我使用的是hoverintent,作为其设置的一部分,它将调用一个函数。我认为这被称为“引用函数”(正确?):

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

    但是,我希望有时重用所述函数并显式传递jquery对象。所以,我把它添加到函数中。

    myFunction($myObject){
    }
    

    现在的挑战是确定函数何时被hoverintent引用或被显式调用。我的想法是检查$(this)是否包含特定的dom元素:

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

    但是…我有问题。如果我同时注销$(this)和$myObject,则结果如下:

    通过悬停意图调用:

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

    通过明确传递对象调用

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

    我可以测试 $(this).is('li') 在第一个场景中,这是真的。

    但是,我不能在第二个测试中完成,就像我尝试执行测试时一样,火狐不喜欢这样:

    g.nodeName is undefined
    

    一个建议是切换到1.4.1并尝试测试相反的via.isplayObject:

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

    这在火狐中很好用。然而,IE8总是返回true。

    我的问题:

    1. 我的逻辑仅仅是从hoverintent和直接调用函数的方式上偏离了吗?

    2. 如果没有,是否有一种方法可以一致地测试,以查看我是否已经显式地将对象传递给了函数中的变量?

    3 回复  |  直到 16 年前
        1
  •  3
  •   Pointy    16 年前

    我会完全不一样的。首先,让一个函数把jquery对象作为参数是很奇怪的。按照jquery的方式,将您的函数放入jquery插件中。为了在您的hoverintent配置中使用,您可以将函数包装在另一个小函数中,或者使用新的(1.4)jquery.proxy()函数来完成此操作。

        2
  •  1
  •   karim79    16 年前

    与其传递对象,不如传递一个简单的布尔值来指示从何处调用它,例如:

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

    还是我完全没抓住要点?

        3
  •  1
  •   Shog9    16 年前

    你让这变得不必要的复杂。只需为传递函数期望的参数的回调使用包装器:

    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
    };
    

    …然后您可以跳过函数内部的检查:

    myFunction($myObject)
    {
         $myObject.doSomething...
    }
    
    推荐文章