3

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>
anbcodes
  • 849
  • 6
  • 15
xaander1
  • 1,064
  • 2
  • 12
  • 40

2 Answers2

4

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.

IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26
0

document.getElementById("button").onclick = this.method1; or you have to do the old var _this = this; And then call _this.method1(event);

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 = this.method1;
  }

}

new Example('alexander', '23');
<button id="button"> Click me </button>
Chris Hemmens
  • 367
  • 2
  • 11