Search code examples
javascriptnode.jslistenereventemitter

Javascript - TypeError: listener must be a function


Yet another 'listener must be a function' error. I double checked all my parameters, checked for correct syntax etc but still can't find where the problem is:

Here are my snippets of code.

in login.js:

global.eventEmitter = require('./helpers/EventEmitter.js');
var packetSwitch = require('./handlers/PacketSwitch.js');
global.ackHandler = require('./handlers/ACKPacketHandler.js');
...
global.eventEmitter.createAndFireEvent('opCodeReceived',packetSwitch.switch(opcode, decrypted, sock));

in PacketSwitch.js:

var packetHandler = require('./PacketHandler.js');
exports.switch = function(opcode, data, sock) {
    switch (opcode) {
        case 1:
            eventEmitter.createAndFireEvent('reqLoginReceived', packetHandler.handleLoginReq(data, sock));
            break;
        case 2:
            eventEmitter.createAndFireEvent('reqDateReceived', packetHandler.handleDateReq(data, sock));
            break;
        default:
            eventEmitter.createAndFireEvent('unknownReceived', packetHandler.handleUnknown(data, sock));
    }
};

let's suppose it enters case 2: in PacketHandler.js:

exports.handleDateReq = function(data, sock) {
    global.eventEmitter.createAndFireEvent('handleDateAck', global.ackHandler.handleDateAck(sock));
};

in ACKPacketHandler.js:

exports.handleDateAck = function(sock) {
    sock.write("Test!");
};

in EventEmitter.js:

var eventEmitter = require('events');
const myEmitter = new eventEmitter.EventEmitter();

exports.createAndFireEvent = function(event, callback) {
    myEmitter.on(event, callback);
    myEmitter.emit(event);
};

And here's a screenshot of the error I get: https://gyazo.com/6047c5917f937aa33f29f9fc40cdf5f7


Solution

  • Your packet handler functions (e.g. handleDateAck()) are not returning functions. In fact, they don't seem to be returning anything. The return value is what you're currently using as the listener function passed to emitter.on().