38 lines
732 B
JavaScript
38 lines
732 B
JavaScript
class Event {
|
|
firings = []
|
|
subscriptions = []
|
|
|
|
constructor(name) {
|
|
this.name = name
|
|
}
|
|
|
|
subscribe(handler) {
|
|
if ( typeof handler !== 'function' ) {
|
|
throw new TypeError('Event subscription handlers must be functions.')
|
|
}
|
|
|
|
this.subscriptions.push(handler)
|
|
}
|
|
|
|
async fire(...args) {
|
|
this.firings.push({ args })
|
|
|
|
return Promise.all(this.subscriptions.map(x => x(...args)))
|
|
}
|
|
}
|
|
|
|
class EventBusService {
|
|
_events = {}
|
|
|
|
event(name) {
|
|
if ( !this._events[name] ) {
|
|
this._events[name] = new Event(name)
|
|
}
|
|
|
|
return this._events[name]
|
|
}
|
|
}
|
|
|
|
const event_bus = new EventBusService()
|
|
export { event_bus, Event }
|