简体   繁体   English

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

[英]Using a class function as an event listener in NodeJS

I have the following code:我有以下代码:

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

In the class constructor and在类构造函数和

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

As a function to the class.作为类的函数。 The class is called PlayMessage.该类称为 PlayMessage。

I get an error saying:我收到一条错误消息:

events.js:130 throw TypeError('listener must be a function'); events.js:130 throw TypeError('listener must be a function');

Talking about the context.on( ... ) line I pasted above.谈论我粘贴在上面的 context.on( ... ) 行。

How should I be using the class function as a listener?我应该如何使用类函数作为侦听器?

Generally speaking, when passing functions to event handlers that rely on a bound context ( this ) like prototype methods, you have to manually bind the context before passing.一般来说,当将函数传递给依赖绑定上下文( this )的事件处理程序时,如原型方法,您必须在传递之前手动绑定上下文。

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

This ensures that the this value within handleHangup is the instance of the "class" you expect.这确保handleHangup中的this值是您期望的“类”的实例。

More info on the Function method .bind() 关于Function方法.bind()更多信息

The issue was that I was trying to declare a class without "new" so none of the prototyped functions existed.问题是我试图声明一个没有“new”的类,所以没有原型函数存在。 That's an amazing learning experience for me.这对我来说是一次了不起的学习经历。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM