I have multiple html files and they each have associated js files mainly for DOM manipulations and also socket.io functionality. However, I can't figure out how to have the same socket.id for these different javascript files. I can maybe merge these js files together into one, but that would be a regress.
I tried making a js module socket.js:
import { io } from 'https://cdn.socket.io/4.3.2/socket.io.esm.min.js';
export const socket = io()
and then imported this in my js files, but as I soon realized this wasn't working.
I was trying the same thing today and came across your question. My solution was this:
main.js is loaded on every page load.
an IIFE runs which sets a variable in my emitter file with the socket via socket.on('connect', ()=>{})
It also just runs a function containing all socket.on(msg,()=>{}), passing the socket.
I can put all my socket message functions into emitters.js. and all received messages into received.js
I haven't found any issues yet, but I'm not yet sure if this is standard practice. I couldn't find much info on this exact question, so hope this helps.
main.js
import socketEmitters from './emitters';
import socketRoutes from './socketRoutes';
(function () {
const socket = io();
socketReceived(socket);
socket.on('connect', () => {
socketEmitters().getSocketInstance(socket);
});
}());
emitters.js
let socket = null;
export default function socketEmitters() {
return {
emitBtnEvent(toggle, msg) {
socket.emit(msg, true);
},
getSocketInstance(socketReceived) {
socket = socketReceived;
}
};
}
received.js
export default function socketRoutes(socket) {
socket.on('receivedMsg', () => {...});
}