I can't figure out why I can't make my server to run emit function.
Here's 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...
}
The listener is:
this.on('start',function(){
console.log("wtf");
});
All the console types is this:
here
here-2
Any idea why it wont print 'wtf'
?
Many objects in a Node emit events, for example, a net. Server emits an event each time a peer connects to it, an fs. readStream emits an event when the file is opened. All objects which emit events are the instances of events.
To create an event emitter, we need to create an instance of the event emitter instance from the events module in NodeJS. Note: I'm using Typescript instead of JavaScript. import { EventEmitter } from 'events';const eventEmitter = new EventEmitter(); This will create an EventEmitter instance.
Node. js uses events module to create and handle custom events. The EventEmitter class can be used to create and handle custom events module.
Well, we're missing some code, but I'm pretty sure this
in the listen
callback won't be your myServer
object.
You should cache a reference to it outside the callback, and use that reference...
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
the outer this
value to 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");
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With