将jQuery引用传递给回调或插件的标准方法

时间:2013-03-21 09:28:24

标签: javascript scope jquery-callback

传递缓存jQuery引用的推荐方法是什么,例如如果函数在$domContainer之前和之外定义,var $domContainer = $('#container');中的$(document).ready()可用作回调函数吗?

示例:

<script src="/plugins.js"></script>

在此可重复使用功能的外部文件中

function rowAction ( event ) { // how do I get context here?

  // how can I access $domTable and $domFilters
  // I can access $(event.target) and traverse the dom
  // back to $domTable, but $domTable is not defined
  // in the external file, although a reference is cached
  // in the local scope of $(document).ready();
  // likewise, $domTable could be accessed through event.delegateTarget
  // however, how can I pass $domFilters, and other vars?

}

在主脚本中

<script src="/scripts.js"></script>

准备好标准文件

$(document).ready(function(){

    // Cached References
    var $domFilters = $('#form .filter'), // more than 1 reference returned
        $domTable   = $('#results');      // 1 reference returned

    $domTable.on('click','.menu',rowAction);// reference function in plugins.js
    // how do I pass $domFilters to rowAction to avoid dom lookups?
    // I could pass $domFilters to a plugin like $(...).plugin({f:$domFilters});
    // if it had optional arguments, but if it's not a plugin, what's the
    // equivalent way to do it?
});

接近这个的方法是使用内联函数来包装回调函数名吗?

任何指向标准做法的指针也会受到欢迎。

2 个答案:

答案 0 :(得分:0)

如果您要访问$ domTable,可以使用事件对象的event.delegateTarget属性,而无需遍历dom。您必须将它包装在jQuery对象中。

修改

将上下文和额外属性传递给外部函数的标准方法是使用call()apply() jQuery有自己的包装,也称为proxy()

在使用$domTable的示例中,上下文已作为选择器的目标传递,因此您可以使用所需的所有内容。

在你的$domFilters示例中,没有事件对象作为上下文传递,因为事件被映射到dom中的实际事件,而你拥有的只有一个集合,所以你不能使用该函数,因为它依赖在事件对象上。

如果我在传递上下文时从集合中调用另一个函数,我会使用类似的东西。

$domFilters = $('#form .filter');
$domFilters.each(function(){

    // Call the external function passing the jQuery wrapped item
    // as the context.
    externalFunction.call($(this));

});


// Your external function
function externalFunction(){

// 'this' would now refer to the context passed in call.
// i.e your $(.filter) item.

}

您的实用程序函数必须设计为能够处理作为上下文传递给它的任何内容以及任何其他参数。

答案 1 :(得分:0)

您可以通过定义NameSpace来遵循模块化方法。那你就不用准备了。

//These four will be open
var objects, handlers, bindings,
NameSpace = {

    //This is where you cache references
    objects: {
        domcontainer: $('.domcontainer')
    },

    //Do the events to handlers bindings
    bindings: function(){
        domcontainer.on('click', handlers.clickCallback)
    }

    //The actual handlers
    handlers: {
        clickCallback: function(e){
            //Do something
        }
    },

    //Initial things
    init: function(){
        objects = this.objects;
        handlers = this.handlers;

        //This will start the handler binding.
        this.bindings();
    }
};

$(function () {
NameSpace.init();  
});

如果要动态添加对象,则可以在对象内添加引用作为返回实际对象引用的函数。无论何时需要引用一个对象,它都可以使用,从而避免DOM查找。