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

210
Views
Socket.io emit event multiple times

for example when i join room-1 then room-2 then room-3 and send message in room-3 that message will be emitted 3 times, when it should get sent just one time. i'm using vanilla JavaScript in the client side

server side

namespaces.forEach(namespace => {
  // join namespace
  io.of(namespace.endpoint).on('connection', socket => {

    console.log(`${socket.id} has joined the ${namespace.endpoint}`)
    socket.emit('nsRooms', {data: namespace.rooms})
    // Join room
    socket.on('joinRoom', async (payload, cb) => {
      const room = Array.from(socket.rooms)[1]
      room && socket.leave(room)
      socket.join(payload.data.roomName)
      const numOfMem = await io.of(payload.data.nsp).in(payload.data.roomName).allSockets()
      cb(Array.from(numOfMem).length)
    })

    socket.on('sendMessage', payload => {
      const room = Array.from(socket.rooms)[1]
      const nsp =  socket.nsp.name
      io.of(nsp).to(room).emit('updateMessage', payload)
    })

  })
})

client side \
Here is when i join rooms and send messages

function joinRoom(roomName) {
  form.removeEventListener('submit', e => submitMsg(e))
  nsSocket.emit('joinRoom', {data: {nsp: nsSocket.nsp, roomName}}, numberOfMember => {
    document.getElementById('current-room').innerHTML = `<span class="curr-room-text">${roomName}</span> <span class="curr-room-num-users">Users: ${numberOfMember}<span class="glyphicon glyphicon-user"></span></span>`
  })

  messages.innerHTML = ''
  nsSocket.on('updateMessage', payload => {
    messages.innerHTML += 
    `
        <li>
          <div class="user-image">
              <img src="https://via.placeholder.com/30" />
          </div>
          <div class="user-message">
              <div class="user-name-time">rbunch <span>${new Date(Date.now()).toDateString()}</span></div>
              <div class="message-text">${payload.data}</div>
          </div>
        </li>
    `
  })
}

form.addEventListener('submit', e => submitMsg(e))

function submitMsg(e) {
  e.preventDefault()
  const msg = userMessage.value
  msg.length > 0 && nsSocket.emit('sendMessage', {data: msg})
  userMessage.value = ''
}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This happens because removeEventListener needs to work with the exact same function reference that was registered, and (e) => submitMsg(e) creates a new lambda all the time. Which means that each time you join a room, a new event handler will be added, without removing the old one.

I created a quick sample app here with the following code that would fix your issue. If you click 'Join some room' three times and then click 'Send message', only one console.log will appear (expand the console on the right hand side to see the result).

const testBtn = document.getElementById('joinRoom');
const form = document.getElementById('chatForm');

testBtn.addEventListener('click', () => {
  form.removeEventListener('submit', submitMsg);

  // ... some other code

  form.addEventListener('submit', submitMsg);
});

submitMsg = (e) => {
  e.preventDefault();

  console.log('submitMsg() called!');

  return false;
}

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!