I have some code that is supposed to listen for certain events and handle them, but either the events are never actually emitted, or the listener just never catches them.
There are two modules here: the server that listens, and the app that handles (the app is the main module).
server.js:
var events = require('events'),
util = require('util'),
dgram = require('dgram');
var Server = function() {
this.self = this;
events.EventEmitter.call(this);
this.socket = dgram.createSocket('udp4');
this.init = function(port) {
this.socket.bind(port);
console.log('Listening on port ' + port);
}
this.socket.on('message', function(buf, rinfo) {
var rawInfo = buf.toString().split('&');
var data = {};
for (var i = 0; i < rawInfo.length; i++) {
var key = rawInfo[i].split('=')[0];
var val = rawInfo[i].split('=')[1];
data[key] = val;
}
var type = data.type;
console.log('emitting event type ' + type);
this.emit(type, data);
});
};
util.inherits(Server, events.EventEmitter);
// exports
module.exports = Server;
(this is the only possible object to be created):
{ type: 'login',
name: 'x3chaos',
displayname: 'x3chaos',
world: 'world' }
app.js:
var dgram = require('dgram');
var Server = require('./server');
var server = new Server();
server.init(41234);
// FIXME
server.on('login', function(data) {
console.log('received data');
console.log(data);
});
What's the problem here: is the event not firing or is the listener not listening?
It might also just be something I'm missing. You know what they say about two heads...
TIA :)
I think that this.emit wont work because you're in a callback, and this wont refer to the Server instance but to the callback context. Upthere, instead of this.self=this try to do var self=this and then inside the callback do self.emit...