Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda