发射事件不会触发
我排放事件只是不想开火。 我在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 });
你的这个关键字失去了“newClient”对象的范围,你应该这样做。
var self = this;
然后,在监听器内部调用
newClient.on('loggedOn', function() { console.log('Logged in.'); self.emit('iConnected'); // change this to self });
为了使其工作。
看看这个链接类通过引用调用原型函数时失去“this”范围
这是一个范围问题。 现在所有的工作都很好。
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;