简体   繁体   English

将EventEmitter迁移到ES6

[英]Migrating EventEmitter to ES6

I'm getting an error that getToken is undefined when called as below and after transpiling with gulp-babel. 我收到一个错误,如下所述以及使用gulp-babel进行编译后,getToken未定义。 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? 我认为这与util继承有关,后者可能试图获取ES5代码并将其应用到ES6所做的事情有很大不同的区域?

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: 根据构造函数中对events.EventEmitter的调用来判断,您可能还使用以下代码:

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

This breaks the Report class (not sure why, but I can reproduce the problem). 这破坏了Report类(不确定原因,但是我可以重现该问题)。

Instead, use ES6-style inheritance: 相反,请使用ES6样式的继承:

class Report extends events.EventEmitter {

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

  getToken(cb) { ... }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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