factor_za
factor_za

Reputation: 119

Socket.io create a separate event handler file

I have crated a socket connection, and at the moment I am looking to just clean up and make everything well organized.

Here is a image of my current file structure FILE STRUCTURE

So what I am wanting to do is take

socket.on("send message", function(data){
    io.sockets.emit("new message", data);
});

and put it in the file called socketEvents.js which is located in main --> js.

However I am not 100% sure on how to include that file on successful connection. I have tried using something like require(); but to no avail. Is there a standard method of including a separate file to run events? Or is it not good practice?

EDIT:

Here is a jsfiddle just to have all the code available: https://jsfiddle.net/7qya7j18/

Upvotes: 0

Views: 1147

Answers (1)

jfriend00
jfriend00

Reputation: 707248

You can just move all your socket.io code to another module and just pass it the server upon initialization. This answer would have been a lot easier to write if you included your code in your question via text (not via an image) so please do that in the future.

Main module:

var express = require("express"),
    app = express(),
    server = require("http").createServer(app);

server.listen(3000, function() {
    console.log("Server is running");
});

app.use(express.static("main"));

// now load and initialize my socket.io module
require('./mysockets')(server);

mySockets module:

var io = require("socket.io");

// declare module constructor that is passed the http server to bind to
module.exports = function(server) {
     io.listen(server);

     io.on("connection", function(socket) {
         // player has connected
         console.log("Player connected");

         socket.on("disconnect", function() {
             console.log("Player disconnected");
         });

         socket.on("send message", function(data) {
             io.emit("new message", data);
         });
     });
};

Upvotes: 2

Related Questions