I have a simple TypeScript class with a private function that should get called, when the user clicks a button. The click event is bound via jQuery click()
event in the constructor
HTML
<div id="foobar">
<h2>Foo</h2>
<button type="button">Bar</button>
</div>
TS
$(() => {
var foo = new Bar($("#foobar"));
})
class Bar {
private view: JQuery;
private button: JQuery;
constructor(view: JQuery) {
// Fields
this.view = view;
this.button = view.find("button");
// Events
this.button.click(() => { this.buttonClick() });
}
private buttonClick() {
this.view.find("h2").css("background-color", "red");
}
}
https://jsfiddle.net/z4vo5u5d/18781/
But somehow, when executing the script, the console complains that buttonClick
is not a function. What am I missing here?
I suppose it's a problem with "this" in TypeScript. But I can't figure out why.
Edited: as @Amadan mentioned:
this.button.click(() => { this.buttonClick() });
is translated incorrectly by jsfiddle into
this.button.click(function () { this.buttonClick(); });
Meanwhile, the compiler at typescriptlang.org/play translates it correctly as:
var _this = this;
...
this.button.click(function () { _this.buttonClick(); });