Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
Using socket.io client with mutliple modules

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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', () => {...});

}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda