打字稿未捕获的类型错误:从 jquery 事件处理程序调用函数时不是函数

Kol*_*kov 1 javascript typescript typescript2.0

打字稿新手,试图找出为什么这不起作用:

我有以下类定义:

class SliderRange {

    updateSliderText(lowId: JQuery, highId: JQuery) {
        //do some updates
    }

    constructor(public uiId: string, lowDisplay: JQuery, highDisplay: JQuery) {
        //register the events that tie ui to the set methods here.
        this.primaryUi().on("input", function () {
            this.updateSliderText(lowDisplay, highDisplay);
        });

        this.secondaryUi().on("input", function () {
            this.updateSliderText(lowDisplay, highDisplay);
        }); 
    }

    private primaryUi() : JQuery {
        return $(`.original#${this.uiId}`);
    }
    private secondaryUi(): JQuery {
        return $(`.ghost#${this.uiId}`);
    }
}
Run Code Online (Sandbox Code Playgroud)

事件被正确触发,但是当它们被触发时,浏览器会抱怨 this.updateSliderText 不是一个函数。在浏览器中查看,这并没有被 Typescript 取代,而是引用了 JQuery 对象(primaryUi 或 secondaryUi)。然而 IntelliSense 正确导航到正确的 updateSliderText 函数,这让我相信它应该编译成正确引用该函数的 javascript。

如何在 jquery 事件处理程序中引用属于该类的函数?

谢谢你。

Jor*_*lez 5

this您调用您的上下文this.updateSliderText是错误的。

您需要一个箭头函数(正是出于这个原因而发明的)或通过绑定它来使用旧样式:

this.primaryUi().on("input", () => { // Yay, cool arrow functions.
    this.updateSliderText(lowDisplay, highDisplay);
});

this.primaryUi().on("input", (function() {
    this.updateSliderText(lowDisplay, highDisplay);
}).bind(this)); // yay...? old-bind-style
Run Code Online (Sandbox Code Playgroud)

很酷的 TypeScript 方法是箭头之一。