NodeJS EventEmitter with TypeScript class

boop picture boop · Nov 15, 2015 · Viewed 25.3k times · Source

Is it possible to use NodeJS' events.EventEmitter with a TypeScript class? If yes, how?

I've tried countless variations in the last hours to get this working, so I won't list any of them.

What I basically want to do:

export class Database{
    constructor(cfg:IDatabaseConfiguration) {
        // events.EventEmitter.call(this); 
        mongoose.connect(cfg.getConnectionString(), cfg.getCredentials(), function (err:any) {
            if (err)
                this.emit('error', err);
            else
                this.emit('ready');
        });
    }
}

Answer

Dominik Palo picture Dominik Palo · Sep 11, 2016

New approach:

///<reference path="./typings/node/node.d.ts" />

import {EventEmitter} from 'events';

class Database extends EventEmitter {
    constructor() {
        super();
        this.emit('ready');
    }
}

new Database();