Question I encountered in an interview

const solution = (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);
        }
    }
    
    let emi = new Emitter(messages);
    let rec = new Receiver();
    emi.setEvent(rec.ping);
    emi.trigger();
    console.log(rec.messages); // []
    console.log(emi.messages) // ['hi','hola','hi','hola']
}

solution(['hi','hola']);

Why is the receiver not receiving any messages and how to fix it?

Hi imdoom,

As far as I can tell it’s a context/binding issue

emi.setEvent(rec.ping);

ping’s this will refer to the context that it is called in i.e. the emitter emi.

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

One solution is to bind ping to the receiver.

emi.setEvent(rec.ping.bind(rec)) // this will now be bound to the receiver

That’s my take, not sure if I passed :slight_smile:

edit: just tested that and this was my output

emi.setEvent(rec.ping.bind(rec));
emi.trigger();
console.log(rec.messages); // ['hi','hola']
console.log(emi.messages) // ['hi','hola']
1 Like

Thanks. it worked.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.