Typescript Uncaught TypeError: is not a function when calling function from jquery event handler
Typescript Uncaught TypeError: is not a function when calling function from jquery event handler
打字稿新手,想弄清楚为什么这不起作用:
我有以下 class 定义:
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}`);
}
}
事件被正确触发,但是当它们被触发时,浏览器抱怨 this.updateSliderText 不是一个函数。在浏览器中查看,这并没有被 Typescript 取代,而是引用 JQuery 对象(primaryUi 或 secondaryUi)。然而 IntelliSense 正确导航到正确的 updateSliderText 函数,这让我相信它应该编译成正确引用该函数的 javascript。
如何在 jquery 事件处理程序中引用属于 class 的函数?
谢谢。
您调用 this.updateSliderText
的 this
上下文错误。
你需要一个箭头函数(它们正是出于这个原因而发明的)或者通过绑定它来使用旧样式:
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
最酷的TypeScript方法是箭头一
打字稿新手,想弄清楚为什么这不起作用:
我有以下 class 定义:
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}`);
}
}
事件被正确触发,但是当它们被触发时,浏览器抱怨 this.updateSliderText 不是一个函数。在浏览器中查看,这并没有被 Typescript 取代,而是引用 JQuery 对象(primaryUi 或 secondaryUi)。然而 IntelliSense 正确导航到正确的 updateSliderText 函数,这让我相信它应该编译成正确引用该函数的 javascript。
如何在 jquery 事件处理程序中引用属于 class 的函数?
谢谢。
您调用 this.updateSliderText
的 this
上下文错误。
你需要一个箭头函数(它们正是出于这个原因而发明的)或者通过绑定它来使用旧样式:
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
最酷的TypeScript方法是箭头一