2015-10-17 90 views
1

我发射的事件就是不想发射。我是nodejs的新成员,对于错误的错误感到抱歉,但是我几个小时都无法解决它。发射事件不会发射

客户端模块

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 
}); 
+0

从哪里来的“客户端”模块?在var Client = require('client'); –

+0

该模块有效。我的意思是他的事件(loggedOn,loggedOff,错误)的作品。所以现在我想进一步传送它们。 – SLI

+1

很难测试你在做什么,因为我不是很明白什么是,但是我可以在这里看到两件事情,当你使用“var newClient = new Client(尝试在构造函数中使用相同名称的newClient );”并且可能你在事件监听器函数内部放弃了这个范围。可能这可以帮助http://stackoverflow.com/questions/19457294/class-loses-this-scope-when-calling-prototype-functions-by-reference –

回答

2

关键字输“newClient”对象的范围,你应该做的东西等。

var self = this; 

然后,听众里面调用作为

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

为了使它的工作原理。

看看这个链接Class loses "this" scope when calling prototype functions by reference

2

这是一个范围的问题。现在所有的工作都很好。

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

    var self = this; // this help's me 

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

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

    newClient.on('loggedOff', function() { 
     console.log('Disconnected.'); 
     self.emit('iDisconnected'); // change this to self 
    }); 

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

module.exports = newClient; 
+0

不错,很好的工作。 –