【问题标题】:node.js EventEmitter causes scope problemsnode.js EventEmitter 导致范围问题
【发布时间】:2013-03-10 19:00:06
【问题描述】:

在使用 nodejs 事件系统时,我遇到了一个烦人的问题。如下代码所示,当监听器捕获事件时,事件发射器对象在回调函数中拥有“this”,而不是监听器。

如果将回调放在监听器的构造函数中,问题不大,因为除了指针'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();

【问题讨论】:

标签: node.js event-handling this


【解决方案1】:

尝试将侦听器显式绑定到回调:

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

【讨论】:

  • 谢谢,这行得通。但是由于项目使用了很多事件链,所以在每个“on”短语之后添加它仍然很烦人。还有其他解决方案吗?
  • 谢谢,这对我很有帮助。
  • 您可以存储this.outside.bind(this)返回的引用,并在必要时使用它...
  • 根据性能表现如何?绑定通常在内部将函数包装在一个自执行函数中以进行范围界定。增加传递范围的可能性不是很好吗?因为像这样,作用域函数是在每个 'ok' 事件上创建的,不是吗?
  • @ThomasFankhauser 不,新的(绑定的)函数只创建一次并为每个事件重复使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-24
  • 2016-08-28
  • 2013-01-29
相关资源
最近更新 更多