Search code examples
javascriptnode.jsemiteventemitter

Using emit function in node.js


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'?


Solution

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