Answer the question
In order to leave comments, you need to log in
How to properly split logic into server socket.io files?
Good afternoon.
I'm trying to separate the Websocket server logic so that all events are not in one file.
Found this example:
const io = require('socket.io')(server)
var Shops = require('./EventHandlers/handShops')
var app = {
allSockets: []
}
io.on('connection', socket => {
var eventHandlers = {
shops: new Shops(app, socket),
}
for (var category in eventHandlers) {
var handler = eventHandlers[category].handler;
for (var event in handler) {
socket.on(event, handler[event])
}
}
app.allSockets.push(socket)
});
var Shops = function (app, socket) {
this.app = app,
this.socket = socket,
this.handler = {
synchShopStatus: synchShopStatus.bind(this),
ping: ping.bind(this)
}
function ping() {
this.socket.emit('message', 'PONG!')
}
function synchShopStatus(text) {
this.app.allSockets.emit('synchShopStatus', text);
}
}
module.exports = Shops
Answer the question
In order to leave comments, you need to log in
Because allSockets is an array, you need to loop through it and already call the socket on the element.
Export the socket to where it is needed.
Read about Dependency Injection in Node.js on Express.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question