Reputation: 629
When using nodejs event system, I met with an annoying problem. As the code below shows, when a listener catch a event, the event emitter object owns 'this' in the callback function instead of the listener.
It's not a big problem if you put the callback in the listener's constructor, because besides pointer 'this', you can still use other variables defined in the constructor's scope, like the 'self' or 'that' way.
But, if the callback is put outside the constructor like the prototype methods, it appears to me that there is no ways to get the listener's 'this'.
Not very sure if there are any other solutions. And also, a little confused about why nodejs event emit use the emitter as the caller install of the listener?
util = require('util');
EventEmitter = require('events').EventEmitter;
var listener = function () {
var pub = new publisher();
var self = this;
pub.on('ok', function () {
console.log('by listener constructor this: ', this instanceof listener);
// output: by listener constructor this: false
console.log('by listener constructor self: ', self instanceof listener);
// output: by listener constructor this: true
})
pub.on('ok', this.outside);
}
listener.prototype.outside = function () {
console.log('by prototype listener this: ', this instanceof listener);
// output: by prototype listener this: false
// how to access to listener's this here?
}
var publisher = function () {
var self = this;
process.nextTick(function () {
self.emit('ok');
})
}
util.inherits(publisher, EventEmitter);
var l = new listener();
Upvotes: 1
Views: 2673
Reputation: 203231
Try binding the listener explicitly to the callback:
pub.on('ok', this.outside.bind(this));
Upvotes: 5