Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!