Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need to send event to the instance after fetching. Javascript Class

I want to call a function from a method. I don’t even know how to ask correctly. test.onload() is called immediately, not after 3 seconds. See code for example, please.

export default class {
  constructor() {
    // some code
    setTimeout(() => {
      this.onload;
    }, 3000);
  }

  onload = (fn) => {
    console.log('loaded event');
    fn();
  };
}

const test = new TEST();

test.onload(function () {
  console.log('from instance');
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are calling the function directly. Somehow you think that will be called when the setTimeout runs which is not the case.

If you want the function "from instance" to be called you need to rethink how you are registering it. You are going to have to store the function somehow and let the timer pick it up and execute it.

Setting it with the constructor

class TEST {
  constructor(callback) {
    this.callback = callback;
    setTimeout(() => this.onload(), 3000);
  }

  onload = () => {
    console.log('loaded event');
    if(this.callback) this.callback();
  };
}

const test = new TEST(function () {
  console.log('from instance');
});

Setting it with a method

class TEST {
  constructor() {
    setTimeout(() => this.onload(), 3000);
  }

  onload = () => {
    console.log('loaded event');
    if(this.callback) this.callback();
  };
  
  registerCallback(callback) {
    this.callback = callback;
  }
}

const test = new TEST();
test.registerCallback(function () {
  console.log('from instance');
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading