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?