2018-10-23 21:39:48 +00:00
|
|
|
import log from './log';
|
|
|
|
|
|
|
|
class EventEmitter {
|
|
|
|
constructor() {
|
|
|
|
this.events = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
addEventListener(event, listener) {
|
|
|
|
if (typeof this.events[event] !== 'object') {
|
|
|
|
this.events[event] = [];
|
|
|
|
}
|
|
|
|
this.events[event].push(listener);
|
|
|
|
return listener;
|
|
|
|
}
|
|
|
|
|
|
|
|
removeListener(event, listener) {
|
|
|
|
if (typeof this.events[event] === 'object') {
|
|
|
|
const idx = this.events[event].indexOf(listener);
|
|
|
|
if (idx > -1) {
|
|
|
|
this.events[event].splice(idx, 1);
|
|
|
|
}
|
|
|
|
if (this.events[event].length === 0) {
|
|
|
|
delete this.events[event];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
emit(event, ...args) {
|
|
|
|
if (typeof this.events[event] === 'object') {
|
2021-09-13 20:41:05 +00:00
|
|
|
this.events[event].forEach(listener => {
|
2018-10-23 21:39:48 +00:00
|
|
|
try {
|
|
|
|
listener.apply(this, args);
|
|
|
|
} catch (e) {
|
2019-08-23 13:18:47 +00:00
|
|
|
log(e);
|
2018-10-23 21:39:48 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const events = new EventEmitter();
|
|
|
|
export default events;
|