2013-03-21 38 views
1

当使用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(); 
+0

https://www.npmjs.com/package/scoped-event-emitter – 2014-12-26 20:48:11

回答

5

尝试明确结合听者回调:

pub.on('ok', this.outside.bind(this)); 
+0

谢谢,这个作品。但是,由于项目使用了大量的事件链,所以在每个“开始”短语后添加这个内容仍然很烦人。其他解决方案? – Jack 2013-03-21 10:27:34

+0

我不这么认为,这就是JS范围的工作原理:) – robertklep 2013-03-21 10:31:01

+0

谢谢,无论如何,这对我有很大的帮助。 – Jack 2013-03-21 10:35:45