我的发射事件只是不想发射。我是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 :(得分: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;
答案 1 :(得分: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