Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  16] [ 4]  / answers: 1 / hits: 8472  / 10 Years ago, thu, july 17, 2014, 12:00:00

I'm handling over 15 different socket events, I'd like to manage certain socket.io events within the modules that are related to those events.



For example, I'd like to have a file named login.js handle the login socket event, and a file named register.js handle 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?


More From » node.js

 Answers
12

I usually split various client related functionality (I usually call them handlers) into individual modules, and then require and use them in whatever file creates the socket.io connection.



Here is an example module, that exports a function which expects to be passed a socket.io client:



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


Which is consumed by a file that creates a new socket, listens for connections, and passes them to the handler, which then listens to events on the client.



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

// .. set up socket.io

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

[#43797] Wednesday, July 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alanisannettep

Total Points: 695
Total Questions: 96
Total Answers: 91

Location: Australia
Member since Sat, May 27, 2023
1 Year ago
;