bring2dip
bring2dip

Reputation: 885

Implementing eventEmitter in my own class in nodejs

i am writing a socket class and it should emit 'socketConnected' event when the socket is connected.For that i have done this.

Socket.prototype.connectEmitter = function(client){
    console.log("Connected");
    console.log(client);
    this.emit('socketConnected',client);
}


    Socket.prototype.connect = function(){
    var client = net.connect({port:this.remotePort, host:this.remoteIp},function(){     
        this.connectEmitter(client);
    });
    client.on('data',this.dataEmitter); 
    client.on('end',function(){
        console.log("Reading End");
    });
}

But when i run this code it says that socket object has no connectEmitter method. Where am i doing it wrong.(i have not posted the whole code here. i have inherited the eventemitter from util)

Upvotes: 0

Views: 130

Answers (1)

Daniel E.
Daniel E.

Reputation: 206

not sure about the details but :

var client = net.connect({port:this.remotePort, host:this.remoteIp},function(){     
    this.connectEmitter(client);
});

"this" in this case is not this as u may expected. because it is used inside a callback function.

try to use

var instance = this;
var client = net.connect({port:this.remotePort, host:this.remoteIp},function(){     
    instance.connectEmitter(client);
});

regards

Upvotes: 2

Related Questions