A
A
Andrey Rudakov2022-01-11 17:05:10
Node.js
Andrey Rudakov, 2022-01-11 17:05:10

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)
});

And in the handShops.js file:
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

But it throws an error: this.app.allSockets.emit is not a function
And I can't figure out why.
Or is there a better way to separate events into files?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Golub, 2022-01-13
@DEMETRA-WORK

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 question

Ask a Question

731 491 924 answers to any question