将 $(this) 传递给绑定的回调函数

Pass $(this) to a Binded Callback Function

我试图了解这两种回调方法之间的区别以及它们如何处理 $(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"); 
});

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

Fiddle http://jsfiddle.net/szrjt6ta/

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

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

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

了解更多关于 apply() here

你可以通过事件,然后使用$(e.target)

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

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 绑定到包装函数,您可以使用 apply or call.

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

Note: While the syntax of this function is almost identical to that of apply(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

 $("#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

更改事件处理程序附件
$("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");
});

Fiddle: https://jsfiddle.net/szrjt6ta/10/