0

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?

matth
  • 6,112
  • 4
  • 37
  • 43

1 Answers1

1

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));
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • That makes sense. I essentially use the publish function, but it's unaware where it came from. If I wrap it using `function (data) { exchange.publish..`, it also passes the object. – matth Dec 02 '13 at 19:43