Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

81
Visualizações
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');
});

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda