Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 988
Itzik984 Avatar asked Jan 06 '12 03:01

Itzik984


People also ask

What does emit do in node JS?

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.

How do I use event emitter in Node?

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.

Why do we use EventEmitter in node JS?

Node. js uses events module to create and handle custom events. The EventEmitter class can be used to create and handle custom events module.


1 Answers

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");
    });
}
like image 99
user1106925 Avatar answered Sep 20 '22 02:09

user1106925