Date: 2024mar23
Language: JavaScript
Q. jQuery: handle an event in a javaScript class
A. This is WRONG:
class MyClass { // WRONG
onClick() {
console.log('hello=' + this.hello); // WONT GET this.hello
}
connect() {
this.hello = 123;
$('#mything).click(this.onClick);
}
}
The problem is that `this` has a different meaning in the click.
So do:
class MyClass { // WORKS
onClick() {
console.log('hello=' + this.hello); // GETS this.hello
}
connect() {
const self = this;
this.hello = 123;
$('#mything).click(function() { self.onClick(); });
}
}
Now, because of the closure onClick()'s this will be the class - instead of the
thing the event is acting on.