ðŸŠī\zansh.in\js

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
}

Google it:

ðŸŒļ addEventListener 🌚 closures 🌷 CustomEvent ðŸŒŧ dispatchEvent 🌞 removeEventListener