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

Time:08-17

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);
  }

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

const test = new TEST();

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

CodePudding user response:

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);
  }

  onl oad = () => {
    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);
  }

  onl oad = () => {
    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');
});

  • Related