当使用nodejs事件系统时,我遇到了一个烦人的问题。如下面的代码所示,当侦听器捕获事件时,事件发射器对象在回调函数中拥有“this”而不是侦听器。node.js EventEmitter导致范围问题
如果将回调放入监听器的构造函数中,这不是一个大问题,因为除了指针'this'之外,还可以使用构造函数作用域中定义的其他变量,如'self'或'that'。
但是,如果将回调放在构造函数之外(如原型方法),则在我看来,没有办法获取侦听器的“this”。
不太确定是否有其他解决方案。此外,为什么nodejs事件发出使用发射器作为侦听器的调用者安装有点困惑?
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();
https://www.npmjs.com/package/scoped-event-emitter – 2014-12-26 20:48:11