2012-01-06 22 views
6

में उत्सर्जन फ़ंक्शन का उपयोग करके मैं यह नहीं समझ सकता कि मैं अपने सर्वर को उत्सर्जित फ़ंक्शन चलाने के लिए क्यों नहीं बना सकता।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' प्रिंट?

उत्तर

15

ठीक है, हमें कुछ कोड याद आ रहे हैं, लेकिन मुझे यकीन है कि 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 कॉलबैक करने के लिए बाहरी 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