1

I searched for an answer to this (simple ?) question, yet, I can't find anything clear.

I'm a java developper trying to fit in the web market, but, as a OOP, many things infurate me.

io.sockets.on('connection', function (socket) {
    console.log("Client has connected! id = [" + socket.id + "]");

    socket.on('disconnect', onPlayerDisconnected(socket));
});

function onPlayerDisconnected(socket) {
    socket.broadcast.emit('player_disconnected', socket.id);

    console.log("Client has disconnected! id = [" + socket.id + "]");
}

Here's the stacktrace :

events.js:219
    throw new TypeError('"listener" argument must be a function');
    ^

TypeError: "listener" argument must be a function

If I use an anonymous function, it works like a charm. Problem is, if I react to an (increasing) number of events, the code won't be maintenable.

So, is there any way to break down the code to smaller functions ?

Bonus question : is it possible to event split the code in multiple .js files ?

Thanks a lot,
A node.js beginner.

Nino DELCEY
  • 652
  • 1
  • 9
  • 25
  • For the includes from another file check [this](http://stackoverflow.com/questions/5797852/in-node-js-how-do-i-include-functions-from-my-other-files) – Ryad Boubaker Apr 14 '17 at 15:34

1 Answers1

3

You're passing in the result of the function onPlayerDisconnected (which appears to be undefined since nothing is returned) to the socket.on('disconnect') handler and not the actual function onPlayerDisconnected which is what it is looking for.

Change the below code which passes the result of onPlayerDisconnected(socket)

socket.on('disconnect', onPlayerDisconnected(socket));

to this code which just passes the actual function onPlayerDisconnected

socket.on('disconnect', onPlayerDisconnected);

peteb
  • 18,552
  • 9
  • 50
  • 62