You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
908 B

export class Event {
constructor(name) {
this.name = name
this.subscriptions = []
}
subscribe(handler) {
if ( typeof handler !== 'function' ) {
throw new TypeError('Event subscription handler must be a function')
}
this.subscriptions.push(handler)
return () => this.subscriptions = this.subscriptions.filter(x => x !== handler)
}
async fire(...args) {
return Promise.all(this.subscriptions.map(x => x(...args)))
}
}
export class EventBus {
static get() {
if ( !this.instance ) {
this.instance = new EventBus()
}
return this.instance
}
constructor() {
this.events = []
}
/** @return Event */
event(name) {
if ( !this.events[name] ) {
this.events[name] = new Event(name)
}
return this.events[name]
}
}