How can I delete one subscriber if the names are the same?

  • 0
    Colleagues, hello.

    export type EventHandler = (...args: any[]) => void
    interface TH {
      event: string;
      handler: EventHandler;
    }
    
    export class EventEmitter {
      private _handlers: TH[] = []
    
      public emit (event: string, data: any) {
        this._handlers.forEach((th) => {
          if (event === th.event) {
            th.handler(data)
          }
        })
      }
    
      public on (event: string, handler: EventHandler) {
        this._handlers.push({
          event,
          handler
        })
      }
    
      public off (event: string) {
        while (true) {
          const index: number = this._handlers.findIndex((th: TH) => th.event === event)
          if (index > -1) {
            this._handlers.splice(index, 1)
          } else {
            break
          }
        }
      }
    }


    const emiter: EventEmitter  = new EventEmitter()
      emiter.on('sex', handler)
      emiter.on('sex', handler)


    Can I delete one of them?
    Or how to do it right.

    For example, how it is done in Vue.
    It has on and off.
    You can subscribe two handlers at once to one event, but then remove one of them using the off method
    JavaScript Anonymous, Apr 25, 2019

  • 1 Answers
  • 0
    obviously you need to use something other than a name for this.

    or it is a link to a handler, then the code will look like emiter.off (event, handler)

    or, as is done in many places, emiter.on () returns an unsubscribe function, then it will be

    const off1 = emiter.on('aaa', handler1)
    const off2 = emiter.on('aaa', handler2)
    off1()




    Like this is done in Vue.

    It has on and off


    it contains the first option:

    https://github.com/vuejs/vue / blob / dev / src / core / ins ...
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!