【问题标题】:Using emit function in node.js在 node.js 中使用 emit 函数
【发布时间】:2012-02-03 21:22:06
【问题描述】:

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

这是我的代码:

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'吗?

【问题讨论】:

    标签: javascript node.js emit eventemitter


    【解决方案1】:

    好吧,我们缺少一些代码,但我很确定 listen 回调中的 this 不会是您的 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 外部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");
        });
    }
    

    【讨论】:

      【解决方案2】:

      对于新手,请确保尽可能使用 ES6 arrow function 将“this”的上下文绑定到您的函数。

      // 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;
      

      【讨论】:

      猜你喜欢
      • 2017-09-22
      • 2018-01-04
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      相关资源
      最近更新 更多