简体   繁体   English

在ES6类中使用EventEmitter

[英]Use EventEmitter in ES6 class

I am trying to get the EventEmitter in my own class running in ES6: 我试图让我自己的类中的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!')} );

but the event is doing nothing ^^ 但事件无所作为^^

Without ES6 i got it working with this code: 没有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);

Does someone know how to do it right in ES6? 有谁知道如何在ES6中做到这一点?

Events are synchronous - you're firing it before you are listening. 事件是同步的 - 你在听之前就开始了它。 Use 使用

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

You could use process.nextTick() to make you code asynchronous. 您可以使用process.nextTick()使代码异步。 Afterwards everything will work as expected. 之后一切都会按预期工作。 This is the note from the node documentation: 这是节点文档中的注释:

The process.nextTick() method adds the callback to the "next tick queue". process.nextTick()方法将回调添加到“下一个滴答队列”。 Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called. 一旦事件循环的当前转弯转到完成,将调用当前在下一个滴答队列中的所有回调。

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

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

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