0

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 :)

ChaoticWeg
  • 291
  • 2
  • 15

1 Answers1

1

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...

eveiga
  • 206
  • 3
  • 9
  • 1
    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... – eveiga Mar 09 '13 at 00:05
  • That was it. :) It was just scope. – ChaoticWeg Mar 09 '13 at 04:15
  • If you want, throw that up as an answer and I'll upvote and accept. Thanks, @eveiga. :) – ChaoticWeg Mar 09 '13 at 04:16