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>