ðŸŠī\zansh.in\js

JavaScript tinkerings.

message-bus

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