简体   繁体   中英

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;

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) { ... }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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