将$(this)传递给Binded回调函数

时间:2015-08-10 13:09:00

标签: javascript jquery callback bind

我试图理解这两种回调方法之间的区别以及它们如何处理$(this)上下文。

工作示例

$("#container").on("click",".button", function() {
    $(this).text("foo");
});

这个过程很好用。但是,如果我想采用不同的方法,我会失去事件的背景。

非工作示例

bindAnEventToAnElement: function(theElement, theEvent, theFunctions) {
    $("body").on(theEvent, theElement, function() {
        theFunctions();
    });
}

bindAnEventToAnElement(".button", "click", function() { 
    $(this).text("foo"); 
});

后者产生未定义的错误。有没有办法在保留事件的上下文的同时处理这样的回调?

小提琴 http://jsfiddle.net/szrjt6ta/

5 个答案:

答案 0 :(得分:2)

AFAIK,jquery在该回调函数中的this引用event.currentTarget值。因此,您还应该传递事件对象并执行以下操作:

 $("#container").on("click", ".button", function () {
     $(this).text("foo");
 });

 theApp = {
     bindAnEventToAnElement: function (theElement, theEvent, theFunctions) {
         $("body").on(theEvent, theElement, function (e) {
             theFunctions.apply(this /* or e.currentTarget */, arguments);
         });
     }
 }

 theApp.bindAnEventToAnElement(".button-two", "click", function () {
     $(this).text("foo");
 });

<强> Working Fiddle

如果我试图解释这个问题,jquery会绑定回调函数,将其作为e.currentTarget传递。但是你在该回调函数中传递另一个回调函数,该函数的作用域不是它的父回调函数,而是window。因此,您需要再次将this绑定到包装函数,您可以使用applycall执行此操作。

答案 1 :(得分:1)

您必须手动将上下文绑定到函数,以便在回调中保留this

$("body").on(theEvent, theElement, function() {
    theFunctions.apply(this);
});

示例 http://jsfiddle.net/szrjt6ta/1/

详细了解apply() here

答案 2 :(得分:0)

您可以传递该事件,然后使用$(e.target)

https://jsfiddle.net/szrjt6ta/3/

答案 3 :(得分:0)

使用.call(this) call()方法调用具有给定此值的函数和单独提供的参数。

  

注意:虽然这个函数的语法几乎与   apply(),根本区别在于call()接受一个参数   list,而apply()接受一个参数数组。

 $("#container").on("click",".button", function() {
        $(this).text("foo");
    });

theApp = {
    bindAnEventToAnElement: function(theEvent, theElement, theFunctions) {
        $("body").on(theEvent, theElement, function() {
            theFunctions.call(this);
        });
    }
}

    theApp.bindAnEventToAnElement("click", ".button-two", function() { 
        $(this).text("fooe");
    });

Fiddle

答案 4 :(得分:0)

更改事件处理程序附件
$("body").on(theEvent, theElement, function() {theFunctions();});

 $("body " + theElement).on(theEvent, theFunctions);

像这样:

<强> HTML:

<div id="container">
    <a class="button">Button</a><br />
    <a class="button-two">Button Binded</a>
</div>

<强> JQuery的:

$("#container").on("click",".button", function() {
    $(this).text("foo");
});

theApp = {
    bindAnEventToAnElement: function(theElement, theEvent, theFunctions) {
        $("body " + theElement).on(theEvent, theFunctions);
    }
}

theApp.bindAnEventToAnElement(".button-two", "click", function() {
    $(this).text("foo");
});

小提琴: https://jsfiddle.net/szrjt6ta/10/

相关问题