繁体   English   中英

在node.js中使用发射功能

[英]Using emit function in node.js

我不知道为什么我不能让我的服务器运行发射功能。

这是我的代码:

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...
}

侦听器是:

this.on('start',function(){
    console.log("wtf");
});

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

here
here-2

知道为什么它不会打印'wtf'吗?

好了,我们缺少一些代码,但我敢肯定, 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");
    });
}

...或bind外部thisbind到回调...

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");
    });
}

对于新手,请确保在可以将“ this”的上下文绑定到函数时使用ES6 箭头函数。

// Automatically bind the context
function() {
}

() => {
}

// You can remove () when there is only one arg
function(arg) {
}

arg => {
}

// inline Arrow function doesn't need { }
// and will automatically return
function(nb) {
  return nb * 2;
}

(nb) => nb * 2;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM