Using emit function in node.js

I cannot understand why I cannot get my server to run the emit function.

Here is my code:

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

Listener:

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

All console types:

 here here-2 

Any idea why it doesn't print 'wtf' ?

+6
source share
1 answer

Well, we are missing code, but I am sure that this in the listen callback will not be your myServer object.

You should cache the link to it outside the callback and use this link ...

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

... or bind external value of this for the callback ...

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

Source: https://habr.com/ru/post/905275/


All Articles