簡體   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