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

386
Visualizações
How does SocketIO have generic .on() events for any given event?

When using SocketIO, receiving any message is done as so:

socket.on("eventname", function() {
    // Whatever
}

But "eventname" can be literally any string of text.

How did they achieve that? How do they have an event listener for each and every possible string? Do they add event listeners AS the messages come in?

I've tried reading the SocketIO source code, but it went right over my head.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The answer can be found looking at the documentation:

From the source code of Socket.IO:

socket.on(eventName, callback)

(inherited from EventEmitter)

From here:

Internally, the EventEmitter keeps track of an object called this.events that maps event names to arrays of event handlers. When a program calls the on method with an event name and event handler, the EventEmitter adds the handler to the array for that event name.

So basically, the socket keeps a map of events, keyed by name, to an array of functions that are called when that event is received.

And if you look at the documentation of EventEmitter.on, you'll see that it is pretty dumb - it does not check that you aren't adding the same function twice:

.on() -> Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

over 4 years ago · Santiago Trujillo 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