Can I split socket.io event listeners into different modules?

I handle over 15 different socket events, I would like to manage specific socket.io events inside the modules associated with these events.

For example, I would like to have a file named login.js handle the socket event login, and a file called register.js handles the registration socket event.

index.js:

socket.on("connection", function (client) {

    console.log("Client connected to socket!");

    client.on("login", function (data) {

        validate(data){

            socket.sockets.emit("login_success", data);

        }

    });

    client.on("register", function (data) {

        register(data){

            socket.sockets.emit("register_success", data);

        }

    });

});

Is there a way that I can put client.on("register", function (data) { ...in one file and client.on("login", function (data) { ...in another?

+4
source share
3 answers

( ) , require , socket.io.

, , , socket.io:

/* register-handler.js */
module.exports = function (client) {
  // registration related behaviour goes here...
  client.on('register', function (data) {
    // do stuff
  });
};

, , , .

/*  main.js */
// require your handlers
var handleRegister = require('./register-handler');

// .. set up socket.io

socket.on('connection', function (client) {
  // register handlers
  handleRegister(client);
});
+13

socket.on("connection", function (client) {

    console.log("Client connected to socket!");

    require('./login')(socket, client);
    require('./register')(socket, client);
});

login.js

module.exports = function(socket, client) {
    client.on("login", function (data) {

        validate(data){

            socket.sockets.emit("login_success", data);

        }

    });
};
+2

, exports require.

.

+1

All Articles