Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript how do I use onclick event on a class method to call another class method? [duplicate]

Tags:

javascript

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>
like image 758
xaander1 Avatar asked May 01 '26 00:05

xaander1


1 Answers

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.

like image 179
IceMetalPunk Avatar answered May 02 '26 14:05

IceMetalPunk