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

170
Vistas
Why do we declare the unsubscribe method for an event emitter in its subscribe method declaration?

I read this implementation of an event emitter on LeetCode and wanted to ask a few questions.

  1. What purpose does it serve to have the release method in the return of the subscribe method? Why can't I make it its own method?
  2. How do I use the unsubscribe method like this and how would I use it if it was its own method?
  3. The author said the reason behind putting the callback inside an object was to be able to add multiple callbacks of the same name. Is that considered good practice?
  4. Any recommendations as to how to make this implementation better (readability, structure)?
  5. Why isn't subscriptions variable defined in a constructor?

Thank you.

class EventEmitter {
  subscriptions = new Map()
  
  subscribe(eventName, callback) {
    if (!this.subscriptions.has(eventName)) {
      this.subscriptions.set(eventName, new Set())
    }
    const newSub = { callback }
    this.subscriptions.get(eventName).add(newSub)
    
    return {
      unsubscribe: () => {
        const evSub = this.subscriptions.get(eventName)
        evSub.delete(newSub)
        if (evSub.size === 0)
          this.subscriptions.delete(eventName)
      }
    }
  }
  
  emit(eventName, ...args) {
    const callbacks = this.subscriptions.get(eventName)
    if (!callbacks) return
    
    for (let c of callbacks) {
      c.callback(...args)
    }
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. What purpose does it serve to have the release method in the return of the subscribe method? Why can't I make it its own method?

Answer 1: In case unsubscribing needs information only available from making the subscription (like a subscription eventName) it makes sense to provide the function directly from the creation. It saves you having to store data needed in the unsubscription process in some intermediary form. You can make it is own method if you want, but still need to return it as in this code:

unsubscribe(eventName) => {
  const evSub = this.subscriptions.get(eventName)
  evSub.delete(newSub)
  if (evSub.size === 0)
    this.subscriptions.delete(eventName)
}

subscribe(eventName, callback) {
  if (!this.subscriptions.has(eventName)) {
    this.subscriptions.set(eventName, new Set())
  }
  const newSub = { callback }
  this.subscriptions.get(eventName).add(newSub)
    
  return () => unsubscribe(eventName);
}
  1. How do I use the unsubscribe method like this and how would I use it if it was its own method?

Answer 2: You store the return value from subscribe some place you can access it, then invoke it if needed by calling unsubscribe(). How it's used is not different whether it's in its own function or not. It still needs to know the eventName so you need the one returned from subscribe. Like in this code:

const unsub = subscribe("event1", () => {});
// then later 
unsub();  // unsubscribe from event1
  1. The author said the reason behind putting the callback inside an object was to be able to add multiple callbacks of the same name. Is that considered good practice?

Answer 3: There's nothing wrong with it. It's a design choice.

  1. Any recommendations as to how to make this implementation better (readability, structure)?

Answer 4: That's personal choice.

  1. Why isn't subscription defined in a constructor?

Answer 5: I assume you're asking about subscriptions variable (plural) and not the subscription function. It's defined as a class variable which doesn't need any initialization specific to a ctor parameter so there's no need to make one. You could put it in a ctor if you wanted to but it just makes the code longer without any real benefit. If the ctor took in some parameters that would affect the initial value of subscriptions then it could be done in the ctor.

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