Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS EventEmitter with TypeScript class

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');
        });
    }
}
like image 294
boop Avatar asked Nov 15 '15 09:11

boop


3 Answers

New approach:

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

import {EventEmitter} from 'events';

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

new Database();
like image 53
Dominik Palo Avatar answered Nov 20 '22 03:11

Dominik Palo


You should download node typings:

$ tsd install node --save

and then just use the following code:

///<reference path="./typings/node/node.d.ts" />
import events = require('events');

class Database{
    constructor() {
        events.EventEmitter.call(this);
    }
}

I simplified it to test your main problem.

Edit: Modified based on your comment:

///<reference path="./typings/node/node.d.ts" />
import events = require('events');

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

new Database();
like image 30
Martin Vseticka Avatar answered Nov 20 '22 02:11

Martin Vseticka


The modern way to download types definitions for NodeJS and EventEmitter particularly is yarn add @types/node or npm install @types/node

like image 2
Yuriy Gavrishov Avatar answered Nov 20 '22 03:11

Yuriy Gavrishov