Using emit function in node.js
Asked Answered
Z

2

6

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

Zemstvo answered 6/1, 2012 at 3:5 Comment(0)
C
15

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");
    });
}
Clericalism answered 6/1, 2012 at 3:6 Comment(0)
B
0

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;
Barrage answered 7/8, 2018 at 11:8 Comment(1)
An arrow function does not bind "this" to any function. It just doesn't have its own "this". So it just takes the context of its enclosing scope. See the site you linked: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… ...Good hint anyway, next time use a comment! :)Dissemble

© 2022 - 2024 — McMap. All rights reserved.