2012-01-06 5 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"); 
    }); 
} 

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

대단히 감사합니다 !!! – Itzik984