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.

I get an error saying:

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

Talking about the context.on( ... ) line I pasted above.

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.

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

This ensures that the this value within handleHangup is the instance of the "class" you expect.

More info on the Function method .bind()

The issue was that I was trying to declare a class without "new" so none of the prototyped functions existed. That's an amazing learning experience for me.