Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question