Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use EventEmitter in ES6 class

I am trying to get the EventEmitter in my own class running in 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:

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?

like image 478
Alaska Avatar asked Jul 09 '16 10:07

Alaska


2 Answers

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();
like image 106
Bergi Avatar answered Nov 13 '22 04:11

Bergi


You could use process.nextTick() to make you code asynchronous. 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". 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);
}
like image 34
user3674318 Avatar answered Nov 13 '22 02:11

user3674318