Search code examples
node.jseventemitter

EventEmitter - Why does the scope of this differ when adding a listener?


I have a custom EventEmitter object, which emits when messages are received. After receiving a message, I'll publish it to a message exchange from an object, which will use a callback defined from that same object. Sample of the exchange function below:

function Exchange() {
    this.events = {
        published: function (data) {
            console.log(data);
        }
    };
}

Exchange.prototype.publish = function (data) {
    this.events.published(data);
};

On my receiving side, I have the custom EventEmitter which emits data:

server.on('data', function (data) {
    exchange.publish(data);
});

This works, but since exchange.publish and the listener uses the same arguments, I wanted to use:

server.on('data', exchange.publish);

This does not work, as the scope of this inside of the publish method changes, resulting in this.events to be undefined. Why does this happen?


Solution

  • You are passing the function itself as the callback, so it's not called as method of the object and this won't refer to the object. See the MDN documentation for more information about this.

    You can use .bind to explicitly bind the function to a certain object:

    server.on('data', exchange.publish.bind(exchange));