Search code examples
javascriptnode.jseventsemit

Emit event doesn't fire


My emit event just don't want to fire. I am new at nodejs, sorry for dumb mistake, but I can't solve it for a few hours.

client module

var Client = require('steam');
var EventEmitter = require('events').EventEmitter;

var newClient = function(user, pass){
    EventEmitter.call(this);

    this.userName = user;
    this.password = pass;

    var newClient = new Client();
    newClient.on('loggedOn', function() {
        console.log('Logged in.'); // this work
        this.emit('iConnected'); // this don't work
    });

    newClient.on('loggedOff', function() {
        console.log('Disconnected.'); // this work
        this.emit('iDisconnected'); // this don't work
    });

    newClient.on('error', function(e) {
        console.log('Error'); // this work
        this.emit('iError'); // this don't work
    });
}
require('util').inherits(newClient, EventEmitter);

module.exports = newClient;

app.js

var client = new newClient('login', 'pass');

client.on('iConnected', function(){
    console.log('iConnected'); // i can't see this event
});

client.on('iError', function(e){
    console.log('iError'); // i can't see this event
});

Solution

  • Your this keyword lose the scope of "newClient" object , you should make something like.

    var self = this;
    

    and then, call inside the listeners as

    newClient.on('loggedOn', function() {
        console.log('Logged in.');
        self.emit('iConnected'); // change this to self
    });
    

    In order to make it works.

    Take a look to this link Class loses "this" scope when calling prototype functions by reference