2012-01-06 18 views
6

emit関数を実行するサーバーを作成できない理由がわかりません。これはnode.jsでemit関数を使用する

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

すべてのコンソールタイプ:

here 
here-2 

任意のアイデアなぜそれ文句を言わない'wtf'を印刷

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

リスナーがある:

は、ここに私のコードですか?

答えて

15

私はいくつかのコードがありませんが、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"); 
    }); 
} 

...またはbindthis値コールバックには...

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

どうもありがとうございました!!! – Itzik984

関連する問題