带有 TypeScript 类的 NodeJS EventEmitter
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33718140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS EventEmitter with TypeScript class
提问by boop
Is it possible to use NodeJS' events.EventEmitter
with a TypeScript class? If yes, how?
是否可以将 NodeJS'events.EventEmitter
与 TypeScript 类一起使用?如果是,如何?
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');
});
}
}
回答by Dominik Palo
New approach:
新的方法:
///<reference path="./typings/node/node.d.ts" />
import {EventEmitter} from 'events';
class Database extends EventEmitter {
constructor() {
super();
this.emit('ready');
}
}
new Database();
回答by Martin Vseticka
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();