在 NodeJS 中使用 class 函数作为事件监听器
Using a class function as an event listener in NodeJS
我有以下代码:
context
.on( 'hangup', this.handleHangup );
在class构造函数和
PlayMessage.prototype.handleHangup = function() {
log.callout.info( "Call [%s]: Client hungup.", this.row.get( 'id' ) );
this.endCall(); // Get out of here
}
作为class的函数。 class 称为 PlayMessage。
我收到一条错误消息:
events.js:130
throw TypeError('listener must be a function');
关于我在上面粘贴的 context.on( ... ) 行。
我应该如何使用 class 函数作为监听器?
问题是我试图在没有 "new" 的情况下声明 class,所以存在 none 个原型函数。这对我来说是一次很棒的学习经历。
一般来说,当将函数传递给依赖绑定上下文(this
)的事件处理程序(如原型方法)时,您必须在传递之前手动绑定上下文。
context
.on( 'hangup', this.handleHangup.bind(this) );
这确保 handleHangup
中的 this
值是您期望的 "class" 的实例。
我有以下代码:
context
.on( 'hangup', this.handleHangup );
在class构造函数和
PlayMessage.prototype.handleHangup = function() {
log.callout.info( "Call [%s]: Client hungup.", this.row.get( 'id' ) );
this.endCall(); // Get out of here
}
作为class的函数。 class 称为 PlayMessage。
我收到一条错误消息:
events.js:130 throw TypeError('listener must be a function');
关于我在上面粘贴的 context.on( ... ) 行。
我应该如何使用 class 函数作为监听器?
问题是我试图在没有 "new" 的情况下声明 class,所以存在 none 个原型函数。这对我来说是一次很棒的学习经历。
一般来说,当将函数传递给依赖绑定上下文(this
)的事件处理程序(如原型方法)时,您必须在传递之前手动绑定上下文。
context
.on( 'hangup', this.handleHangup.bind(this) );
这确保 handleHangup
中的 this
值是您期望的 "class" 的实例。