在ES6类中使用EventEmitter

时间:2016-07-09 10:28:59

标签: javascript node.js inheritance ecmascript-6 eventemitter

我试图让我自己的类中的EventEmitter在ES6中运行:

"use strict";
const EventEmitter = require('events');

class Client extends EventEmitter{

    constructor(token, client_id, client_secret, redirect_uri, code){
        super();
        this.token = token;
        this.client_id = client_id;
        this.client_secret = client_secret;
        this.redirect_uri = redirect_uri;
        this.code = code;
    }

    eventTest(){
        this.emit("event");
        console.log(this.token);
    }
}

let testClient = new Client(1,2,3,4,5);

testClient.eventTest();
testClient.on('event', () => {console.log('triggerd!')} );

但事件无所作为^^

如果没有ES6,我可以使用此代码:

var util = require('util');
var EventEmitter = require('events').EventEmitter;

var Client = function(credentials) {
    var self = this;

    function eventTest() {
        self.emit('event');
    }
};

util.inherits(Client, EventEmitter);

有人知道如何在ES6中做到这一点吗?

2 个答案:

答案 0 :(得分:21)

事件是同步的 - 你在听之前就开始了它。使用

const testClient = new Client(1,2,3,4,5);
testClient.on('event', () => {console.log('triggered!')} );
testClient.eventTest();

答案 1 :(得分:0)

您可以使用process.nextTick()使代码异步。之后一切都会按预期工作。这是节点文档中的注释:

  

process.nextTick()方法将回调添加到" next tick queue"。一旦事件循环的当前转弯转到完成,将调用当前在下一个滴答队列中的所有回调。

eventTest(){
    process.nextTick(() => {
        this.emit("event");
    });
    console.log(this.token);
}