Created
December 24, 2020 18:38
-
-
Save CzBiX/85138bdf6dbd43407311236090adb82a to your computer and use it in GitHub Desktop.
A simple JS Event Bus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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