Got a Problem with Typescript and jQuery. The elements get appended to body and show up but nothing happens when i click the button.
I suppose its something with the this.fooClick() that gets passed to the button but doesnt get called or the wrong jquery elements gets saved to the class variables.
Anyone help?
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();
});
.clickexpects to be passed a function. You are passing the return value offooClick, which isundefined. JavaScript is not as magical as you might think. Functions to bind event listeners are no different from any other function. Whenever you havefoo(bar()),barwill be executed first and its return value will be passed tofoo. If you want to tellfooto executebarat some point, you have to passbaritself:foo(bar).