Simon H
Simon H

Reputation: 21005

Migrating EventEmitter to ES6

I'm getting an error that getToken is undefined when called as below and after transpiling with gulp-babel. Moving the constructor to bottom of class does not help either. Can anyone advise?

I think it has something to do with the util inheriting, which may be trying to take ES5 code and apply it to an area where ES6 does things very differently?

var events = require('events');
var util = require('util');
class Report {

    constructor(private_key, service_email, debug) {
        this.private_key = private_key;
        this.service_email = service_email;
        this.debug = debug || false;

        events.EventEmitter.call(this);

        this.getToken( (err, token) => {
            if (err) throw err;

            return this.emit('ready');
        });
    }

    getToken(cb) {
        ...
    }
}

util.inherits(Report, events.EventEmitter);

module.exports = Report;

Upvotes: 0

Views: 2191

Answers (1)

robertklep
robertklep

Reputation: 203231

Judging by the call to events.EventEmitter in your constructor, you probably also using this:

require('util').inherits(Report, events.EventEmitter);

This breaks the Report class (not sure why, but I can reproduce the problem).

Instead, use ES6-style inheritance:

class Report extends events.EventEmitter {

  constructor(private_key, service_email, debug) {
    super();
    ...
  } 

  getToken(cb) { ... }
}

Upvotes: 10

Related Questions