Skip to content

Instantly share code, notes, and snippets.

@CzBiX
Created December 24, 2020 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CzBiX/85138bdf6dbd43407311236090adb82a to your computer and use it in GitHub Desktop.
Save CzBiX/85138bdf6dbd43407311236090adb82a to your computer and use it in GitHub Desktop.
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