Play with the controls to see how the code works. All code is present in the page, but some scrollback may be necessary to grok everything.
# message-bus
1 min read
Use the existing browser events API to implement a message-bus.
# window.addEventListener()
const log = () =>
console.log('hello, world')
addEventListener(
'DOMContentLoaded',
log
)
# CustomEvent
addEventListener('ð', event => {
console.log('hello, ' + event?.detail)
})
const event = new CustomEvent('ð', {
detail: 'world'
})
dispatchEvent(event)
# emit()
const fireEvent = () =>
emit('ð', 'world')
function emit(name, detail) {
dispatchEvent(
new CustomEvent(name, { detail })
)
}
# on()
const fireEvent = () =>
emit('ð', 'world')
const off = on('ð', msg => {
console.log('hello, ' + msg)
})
function on(eventName, cb) {
const fn = ({ detail }) => cb(detail)
addEventListener(eventName, fn)
return () =>
removeEventListener(eventName, fn)
}
# once()
const fireEvent = () => emit('ð')
once('ð', () => {
console.log('just once')
})
function once(eventName, cb) {
const off = on(
eventName,
detail => (off(), cb(detail))
)
return off
}