1

I can't figure out how to correct the context of my methods.

I have this class:

export default class Handler {

    constructor() {
        // init
    }

    handleMessage(channel, user, message) {
        this.handleDefault(channel, user, message);
    }

    handleDefault(chanenl, user, message) {
        // do stuff
    }
}

it is called by this method and class

export default class Bot {

    constructor() {
        this.irc     = irc // has an event emitter irc.event
        this.handler = new Handler();
        this.readIRC();
    }

    readIRC() {
        this.irc.event.on('message', this.handler.handleMessage);
    }
}

The problem is in the first class inside handleMessage is this not the class anymore but the eventEmitter so I can't call my handleDefault method.

How do I work with contexts corretly in ES6 ?

gempir
  • 1,791
  • 4
  • 22
  • 46

1 Answers1

4

You just have to bind handleMessage to this.handler, either with

  • Function.prototype.bind

    this.irc.event.on('message', this.handler.handleMessage.bind(this.handler));
    
  • or with an Arrow function,

    this.irc.event.on('message', () => this.handler.handleMessage());
    

In both these cases, when the handleMessage function is invoked on message event, the this within handleMessage will refer the this.handle object.


If you like to pass arguments to the event handler, you can define the arrow function like this

this.irc.event.on('message', (err, msg) => this.handler.handleMessage(err, msg));
thefourtheye
  • 233,700
  • 52
  • 457
  • 497