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.
40 lines
785 B
40 lines
785 B
class Event {
|
|
|
|
constructor(name) {
|
|
this.name = name
|
|
this.firings = []
|
|
this.subscriptions = []
|
|
}
|
|
|
|
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 {
|
|
constructor() {
|
|
this._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 }
|