2022-02-10 23:06:24 -06:00
|
|
|
import _ from 'lodash';
|
|
|
|
|
|
|
|
export default class EventBus {
|
|
|
|
constructor() {
|
|
|
|
this._eventListeners = [];
|
|
|
|
}
|
|
|
|
|
2022-04-07 07:06:56 -05:00
|
|
|
registerListener(event, callback, once=false) {
|
2022-02-10 23:06:24 -06:00
|
|
|
this._eventListeners = this._eventListeners || [];
|
|
|
|
this._eventListeners.push({
|
|
|
|
event: event,
|
|
|
|
callback: callback,
|
2022-04-07 07:06:56 -05:00
|
|
|
fired: once ? 'pending' : 'ignore',
|
2022-02-10 23:06:24 -06:00
|
|
|
});
|
2023-10-23 07:13:17 -05:00
|
|
|
|
|
|
|
// helpfull in useEffect where we need to cleanup the listeners.
|
|
|
|
return ()=>{
|
|
|
|
this.deregisterListener(event, callback);
|
|
|
|
};
|
2022-02-10 23:06:24 -06:00
|
|
|
}
|
|
|
|
|
2022-11-20 23:24:15 -06:00
|
|
|
on(...args) {
|
2023-10-23 07:13:17 -05:00
|
|
|
return this.registerListener(...args);
|
2022-11-20 23:24:15 -06:00
|
|
|
}
|
|
|
|
|
2022-11-28 02:16:12 -06:00
|
|
|
once(...args) {
|
2023-10-23 07:13:17 -05:00
|
|
|
return this.registerListener(...args, true);
|
2022-11-28 02:16:12 -06:00
|
|
|
}
|
|
|
|
|
2022-02-10 23:06:24 -06:00
|
|
|
deregisterListener(event, callback) {
|
|
|
|
if(callback) {
|
|
|
|
this._eventListeners = this._eventListeners.filter((e)=>{
|
|
|
|
if(e.event === event) {
|
2023-10-23 07:13:17 -05:00
|
|
|
return e.callback != callback;
|
2022-02-10 23:06:24 -06:00
|
|
|
}
|
2022-04-18 02:20:51 -05:00
|
|
|
return true;
|
2022-02-10 23:06:24 -06:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
this._eventListeners = this._eventListeners.filter((e)=>e.event!=event);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-20 23:24:15 -06:00
|
|
|
off(...args) {
|
|
|
|
this.deregisterListener(...args);
|
|
|
|
}
|
|
|
|
|
2022-02-10 23:06:24 -06:00
|
|
|
fireEvent(event, ...args) {
|
2022-04-07 07:06:56 -05:00
|
|
|
let self = this;
|
2022-02-10 23:06:24 -06:00
|
|
|
Promise.resolve(0).then(()=>{
|
|
|
|
let allListeners = _.filter(this._eventListeners, (e)=>e.event==event);
|
|
|
|
if(allListeners) {
|
|
|
|
for(const listener of allListeners) {
|
|
|
|
Promise.resolve(0).then(()=>{
|
|
|
|
listener.callback(...args);
|
2022-04-07 07:06:56 -05:00
|
|
|
if(listener.fired == 'pending') {
|
|
|
|
self.deregisterListener(event, listener.callback);
|
|
|
|
}
|
2022-02-10 23:06:24 -06:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2022-11-20 23:24:15 -06:00
|
|
|
|
|
|
|
trigger(...args) {
|
|
|
|
this.fireEvent(...args);
|
|
|
|
}
|
2022-02-10 23:06:24 -06:00
|
|
|
}
|