I
I
Igor2020-10-19 22:56:37
JavaScript
Igor, 2020-10-19 22:56:37

How to remove one subscriber if the names are the same?

Colleagues, welcome.

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 one of them be removed?
Or how to do it right.

For example, how it's done in Vue.
It has on and off
You can subscribe two handlers to one event at once, but then delete one of them using the off method

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-10-20
@Robur

obviously you need to use something other than a name to do this.
either this is a link to the handler, then the code will be of the form emiter.off(event, handler)
or, as it is done in many places, emiter.on () returns a function - an unsubscriber, then it will be

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

For example, how it's done in Vue.
It has on and off

in it - the first option:
https://github.com/vuejs/vue/blob/dev/src/core/ins...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question