2014-01-08 99 views
0

我正在编写一个套接字类,它应该在套接字连接时发出'socketConnected'事件。为此,我已经完成了此操作。在nodejs中的自己的类中实现eventEmitter

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

但是,当我运行这段代码它说socket对象没有connectEmitter方法。 我在哪里做错了(我还没有张贴在这里,整个代码,我继承UTIL的eventemitter。)

回答

2

不知道的细节,而是:在这种情况下

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

“本”这不像你预料的那样。因为它在回调函数中使用。

尝试使用

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

问候

+0

我不知道,“这个”,在这种情况下,是不是我的期望。谢谢。非常感激 – bring2dip