javascript - 在 NodeJS 中使用类函数作为事件监听器

标签 javascript node.js class listener dom-events

我有以下代码:

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('listener must be a function');

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

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

最佳答案

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

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

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

More info on the Function method .bind()

关于javascript - 在 NodeJS 中使用类函数作为事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29258425/

相关文章:

node.js - 使用布局时 Jade 模板引擎错误

ruby - 动态获取变量值

javascript - Stripe Checkout 是否泄漏内存?

javascript - AngularJS 不在 ng-repeat 中排序

javascript - 选择选项未更新 HTML 网页中的 'selected' 属性

c++ - 如何在另一个类中访问一个类的成员函数?

c++ - 创建将模板类作为构造函数中的参数的模板类

javascript - javascript( typescript )类中的静态常量

javascript - Knex 数据未插入 postgres

node.js - 如何将变量从一个回调获取到另一个回调?