Reputation: 753
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.
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
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
});
Upvotes: 1
Views: 1693
Reputation: 1371
Your this keyword lose the scope of "newClient" object , you should make something like.
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
Upvotes: 2
Reputation: 753
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;
Upvotes: 2