0

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?

2
  • 1
    What is the value of the this keyword when you call context.on( 'hangup', this.handleHangup );? Commented Mar 25, 2015 at 14:42
  • 1
    If you have problems debugging node.js code have a look at https://nodejs.org/api/debugger.html#debugger_debugger. Commented Mar 25, 2015 at 14:46

2 Answers 2

2

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()

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.