我有以下代码:
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
值是您期望的“类”的实例。
关于javascript - 在 NodeJS 中使用类函数作为事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29258425/