Skip to content

Instantly share code, notes, and snippets.

@CzBiX
Created Dec 24, 2020
Embed
What would you like to do?
A simple JS Event Bus
class EventBus {
subscriptions = {};
on(eventType, callback) {
const id = Symbol('id');
if (!this.subscriptions[eventType]) this.subscriptions[eventType] = {};
this.subscriptions[eventType][id] = callback;
const thiz = this;
return {
id,
eventType,
off() {
thiz.off(eventType, id);
},
};
};
off(eventType, id) {
if (!id) {
delete this.subscriptions[eventType];
return;
}
delete this.subscriptions[eventType][id];
if (Object.getOwnPropertySymbols(this.subscriptions[eventType]).length === 0) {
delete this.subscriptions[eventType];
}
}
once(eventType, callback) {
let s = undefined;
const wrap = (arg) => {
try {
callback(arg);
} finally {
s.off();
}
}
s = this.on(eventType, wrap);
return s;
}
emit(eventType, arg) {
if (!this.subscriptions[eventType]) return;
Object.getOwnPropertySymbols(this.subscriptions[eventType])
.forEach(key => this.subscriptions[eventType][key](arg));
};
}
export default EventBus;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment