简体   繁体   中英

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

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

For new people, make sure to you use the ES6 arrow function whenever you can to bind the context of "this" to your function.

// Automatically bind the context
function() {
}

() => {
}

// You can remove () when there is only one arg
function(arg) {
}

arg => {
}

// inline Arrow function doesn't need { }
// and will automatically return
function(nb) {
  return nb * 2;
}

(nb) => nb * 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM