TransWikia.com

Call a class function from a async class function

Stack Overflow Asked by Toge on December 9, 2021

I want to call a function inside a class from another function inside the same class. This works well with this.myFunction(). But when the calling function is for example triggered by a click eventhandler, this for the class is no longer available.

Normally I would use new MyClass().myFunction()but in this case I am losing values and objects from "the first" instance.

In my case I started an interval, that i want to clear after a button click. But when I create a new instance of my class, the interval is of course not longer available.

How should I call functionToCall() from the myButton.addEventListener("click", function () {? Or is this a generally wrong approach?

MyClass.js

export class MyClass {

constructor() {
 this.refreshIntervalId = 0;
}

functionToCall() {

 clearInterval(this.refreshIntervalId); // this has to be the instance

}

buttonFunction() {

 let myButton = document.getElementById(myButton);

 myButton.addEventListener("click", function () {
  this.functionToCall(); // doesn't work (of course)
 });

}

startInterval() {
 this.refreshIntervalId = setInterval(() => {
   this.buttonFunction()
 }, 1000);
}

}

index.js

import {
  MyClass
} from './MyClass';

let myClass = new MyClass();
myClass.startInterval();

2 Answers

This works very well!

In my case i still needed the clicked button as object too. Binding this means, that you loose this for the clicked Button With the .bind method, you could bind more than one objects (i didn't know that).

Final code:

// listener
    let myButton = document.getElementsByClassName('myButton');
    for (var i = 0; i < myButton.length; ++i) {
      let customVar; // this gets bind with value i
      myButton[i].addEventListener("click", (function () {
        let value = myButton[numbr].getAttribute("data-value");
        this. functionToCall(value);
     }).bind(this,customVar = i));

Answered by Toge on December 9, 2021

If you replace

myButton.addEventListener("click", function () {
   this.functionToCall(); // doesn't work (of course)
});

with

myButton.addEventListener("click", () => {
   this.functionToCall();
});

then within the handler, this will be bound to the this that exists in the scope in which the arrow function was declared. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions for more info.

Alternatively, you can explicitly bind the this value within the function to the "external" this using the Function.bind method:

myButton.addEventListener("click", (function () {
   this.functionToCall();
}).bind(this));

Answered by spender on December 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP