2012-01-06 14 views
6

Non riesco a capire perché non riesco a far funzionare la mia funzione di emettere il mio server.Utilizzo della funzione emit in node.js

Ecco il mio codice:

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

L'ascoltatore è:

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

Tutti i tipi di console è questo:

here 
here-2 

Qualsiasi idea del perché non ci vorrà stampare 'wtf'?

risposta

15

Bene, ci manca un po 'di codice, ma sono abbastanza sicuro che this nella chiamata listen non sarà l'oggetto myServer.

Si dovrebbe memorizzare nella cache un riferimento ad esso al di fuori della richiamata, e l'uso che di riferimento ...

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

... o bind il this valore esterno alla richiamata ...

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

Grazie mille!!! – Itzik984

Problemi correlati