【问题标题】:Using a class function as an event listener in NodeJS在 NodeJS 中使用类函数作为事件监听器
【发布时间】:2015-03-25 14:26:28
【问题描述】:

我有以下代码:

context
    .on( 'hangup', this.handleHangup );

在类构造函数中

PlayMessage.prototype.handleHangup = function() {
    log.callout.info( "Call [%s]: Client hungup.", this.row.get( 'id' ) );
    this.endCall(); // Get out of here
}

作为类的函数。该类称为 PlayMessage。

我收到一条错误消息:

events.js:130 throw TypeError('监听器必须是函数');

谈论我在上面粘贴的 context.on( ... ) 行。

我应该如何使用类函数作为监听器?

【问题讨论】:

标签: javascript node.js class listener dom-events


【解决方案1】:

一般来说,将函数传递给依赖于绑定上下文 (this) 的事件处理程序(如原型方法)时,您必须在传递之前手动绑定上下文。

context
    .on( 'hangup', this.handleHangup.bind(this) );

这确保handleHangup 中的this 值是您期望的“类”的实例。

More info on the Function method .bind()

【讨论】:

    【解决方案2】:

    问题是我试图声明一个没有“新”的类,因此不存在任何原型函数。这对我来说是一次了不起的学习经历。

    【讨论】:

      猜你喜欢
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      相关资源
      最近更新 更多