Friday 14 April 2017

Can't use non-anonymous method with socket.io, "listener" argument must be a function

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.



via Nino Lenoska

No comments:

Post a Comment