0

I'm not sure why this code is not working. The Receiver class instance does not return any messages.

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

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

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

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

    ping(message) {
      this.messages.push(message);
    }
  }

  const myEmitter = new Emitter(messages);
  const myReceiver = new Receiver();

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

  return myReceiver.messages;
};

One simple way to fix this is to pass the Receiver instance to the Emitter constructor, and call the ping() method directly. But I feel like there should be a way to call that function without passing the class.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Daniel
  • 437
  • 1
  • 5
  • 14

0 Answers0