[英]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.
我是nodejs的新手,很抱歉犯了愚蠢的错误,但几个小时后却无法解决。
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 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
});
It was a scope problem. 这是一个范围问题。 Now all work's fine.
现在一切正常。
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;
Your this keyword lose the scope of "newClient" object , you should make something like. 您的此关键字失去了“ newClient”对象的范围,您应该做类似的事情。
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 看一下此链接类通过引用调用原型函数时会丢失“ this”范围
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.