在node.js中使用emit函数

Itz*_*984 6 javascript node.js eventemitter emit

我无法弄清楚为什么我不能让我的服务器运行emit函数.

这是我的代码:

myServer.prototype = new events.EventEmitter;

function myServer(map, port, server) {

    ...

    this.start = function () {
        console.log("here");

        this.server.listen(port, function () {
            console.log(counterLock);
            console.log("here-2");

            this.emit('start');
            this.isStarted = true;
        });
    }
    listener HERE...
}
Run Code Online (Sandbox Code Playgroud)

听众是:

this.on('start',function(){
    console.log("wtf");
});
Run Code Online (Sandbox Code Playgroud)

所有控制台类型都是这样的:

here
here-2
Run Code Online (Sandbox Code Playgroud)

知道它为什么不打印'wtf'

小智 15

好了,我们缺少一些代码,但我敢肯定,thislisten回调不会是你的myServer对象.

您应该在回调之外缓存对它的引用,并使用该引用...

function myServer(map, port, server) {
    this.start = function () {
        console.log("here");

        var my_serv = this; // reference your myServer object

        this.server.listen(port, function () {
            console.log(counterLock);
            console.log("here-2");

            my_serv.emit('start');  // and use it here
            my_serv.isStarted = true;
        });
    }

    this.on('start',function(){
        console.log("wtf");
    });
}
Run Code Online (Sandbox Code Playgroud)

...或回调bind的外部this值...

function myServer(map, port, server) {
    this.start = function () {
        console.log("here");

        this.server.listen(port, function () {
            console.log(counterLock);
            console.log("here-2");

            this.emit('start');
            this.isStarted = true;
        }.bind( this ));  // bind your myServer object to "this" in the callback
    };  

    this.on('start',function(){
        console.log("wtf");
    });
}
Run Code Online (Sandbox Code Playgroud)