jQuery Typescript 中的回调 Class

jQuery Callback inside Typescript Class

Typescript 和 jQuery 有问题。元素附加到正文并显示,但当我单击按钮时没有任何反应。

我想是 this.fooClick() 传递给按钮但没有被调用,或者错误的 jquery 元素被保存到 class 变量。

有人帮忙吗?

test.ts

/// <reference path="jquery.d.ts" />

class foo {

    private button;
    private text;

    constructor() {

        this.button = $('<button>').html("click").click(this.fooClick());
        this.text = $('<p>').html("foo");

        $('body').append(this.button);
        $('body').append(this.text);
    }

    public fooClick() {
        $(this.text).html("bar");
    }

}

$(function() {
    var foobar = new foo();
})

test.js

/// <reference path="jquery.d.ts" />
var foo = (function () {
    function foo() {
        this.button = $('<button>').html("click").click(this.fooClick());
        this.text = $('<p>').html("foo");
        $('body').append(this.button);
        $('body').append(this.text);
    }
    foo.prototype.fooClick = function () {
        $(this.text).html("bar");
    };
    return foo;
})();
$(function () {
    var bar = new foo();
});

注册点击处理程序时,必须向其传递对回调的引用,而非调用回调。实际单击按钮时将发生调用。

因此,你应该这样做:

this.button = $('<button>').html("click").click(this.fooClick);
// notice the removed parentheses

由于 fooClick 期望其 this 值绑定到 foo 的实例,您还应该将其重写为箭头函数:

public fooClick = () => {
    $(this.text).html("bar");
}

当您调用 .click() 时,您希望向其传递一个函数,该函数可以在单击按钮时执行。现在你正在立即执行你的功能:

this.button = $('<button>').html("click").click(this.fooClick());

...这将传递 this.fooClick() 的结果,即 undefined

你可以解决这个问题,方法是传入一个稍后将执行的函数:

this.button = $('<button>').html("click").click(() => this.fooClick());

注意:如图所示,确保使用箭头函数来保留 this 的上下文。