How do I use onclick event on a class method to call another class method?
When I try to do so get this error:
Uncaught TypeError: this.method1 is not a function at HTMLButtonElement.document.getElementById.onclick (example.html:24)
I am suspecting the onclick event accepts only a callback function and not a method.
Is their a workaround?
Here is a sample:
class Example {
constructor(name, age) {
this.name = name;
this.age = age;
this.method2();
}
method1(evt) {
console.log(evt)
alert("Example Rendered")
}
method2() {
document.getElementById("button").onclick = function() {
this.method1(event);
}
}
}
new Example('alexander', '23');
<button id="button"> Click me </button>
The keyword this has different bindings when used inside functions like that. In this case, it's being rebound to refer to the button. Since you're using ES6 classes anyway, you can use the ES6 arrow function notation to create a function that doesn't rebind this:
document.getElementById("button").onclick = event => {
this.method1(event);
}
For completeness of this answer, in ES5, you could do something like this instead:
document.getElementById("button").onclick = this.method1.bind(this);
That makes sure this is bound to the class when the function is run, rather than the button element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With