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

213
Visualizações
Why does my receiver's class instance method not receive any data?

I created a basic emitter and receiver. Please can you let me know why when I console log the receivers messages it returns an empty array?

class Emitter {
  constructor(messages = []) {
    this.messages = messages;
    this.event = () => {};
  }
  setEvent(fn) {
    this.event = fn;
  }
  trigger() {
    this.messages.forEach(message => this.event(message));
  }
}

class Reciever {
  constructor() {
    this.messages = []
  }
  ping(message) {
    console.log(message)
    this.messages.push(message)
  }
}

const myReciever = new Reciever();
const myEmitter = new Emitter(message = ["A", "B", "C"]);

myEmitter.setEvent(myReciever.ping);
myEmitter.trigger();

console.log(myReciever.messages);

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You are losing context on the ping call:

myEmitter.setEvent(myReciever.ping);

You need to bind it.

myEmitter.setEvent(myReciever.ping.bind(myReciever));
about 4 years ago · Juan Pablo Isaza Relatório

0

You are storing everything in the emitter, not the receiver. If you print the emitter, the entries are duplicated.

This is because when you pass in the function to the .setEvent(...) you are using this which - in this scenario - is referring to the messages from the emitter; it lost the context of the object it belongs to.

Like @MinusFour indicated, you need to bind the function instead.

See demo below

class Emitter {
  constructor(messages = []) {
    this.messages = messages;
    this.event = () => {};
  }

  setEvent(fn) {
    this.event = fn;
  }

  trigger() {
    this.messages.forEach(message => this.event(message));
  }
}

class Reciever {
  constructor() {
    this.messages = []
  }

  ping(message) {
    console.log(message)
    this.messages.push(message)
  }
}

const myReciever = new Reciever();
const myEmitter = new Emitter(message = ["A", "B", "C"]);

myEmitter.setEvent(myReciever.ping.bind(myReciever));
myEmitter.trigger();

console.log(myReciever.messages);

about 4 years ago · Juan Pablo Isaza Relatório

0

From the comment above ...

"At the time of setEvent the code doesn't care about the this context of myReciever.ping. ... ping gets assigned to an emitters own event just as function, immediately getting oblivious where it originally did belong to."

Besides the already suggested solution of actively binding thisArg to its method, one also can adapt the code in a way that one can or has to pass to setEvent a methods's target/context alongside the method/function itself. At trigger time the method then will be called within this stored context ...

class Emitter {
  constructor(messages = []) {
    this.messages = messages;
    this.handler = () => {};
    this.target = null;
  }
  setEvent(handler, target) {
    // `setEvent` might be better renamed to
    // `setHandler` or `assignHandler`, etc.
    this.handler = handler ?? (() => {});
    this.target = target ?? null;
  }
  trigger() {
    this.messages.forEach(message =>
      this.handler.call(this.target, message)
    );
  }
}

class Reciever {
  constructor() {
    this.messages = []
  }
  ping(message) {
    console.log(message)
    this.messages.push(message)
  }
}

const myReciever = new Reciever();
const myEmitter = new Emitter(message = ["A", "B", "C"]);

myEmitter.setEvent(myReciever.ping, myReciever);
myEmitter.trigger();

console.log(myReciever.messages);

about 4 years ago · Juan Pablo Isaza 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