Skip to content

Instantly share code, notes, and snippets.

@stevebrownlee
Created May 14, 2020 14:03
Show Gist options
  • Save stevebrownlee/fbfa0e629db2eb4462ecd8de9fb517f0 to your computer and use it in GitHub Desktop.
Save stevebrownlee/fbfa0e629db2eb4462ecd8de9fb517f0 to your computer and use it in GitHub Desktop.
Bare bones event broker
const channels = {}
export const radio = {
listen (event, callback) {
if (!channels[event]) {
channels[event] = []
}
channels[event].push(callback)
},
broadcast (event, data = {}) {
const listeners = channels[event] || []
for (const callback of listeners) {
callback(data)
}
}
}
// Import the radio
import { radio } from "./broker.js"
// Listen on a channel
radio.listen("potteryCreated", data => {
// Use the data that was broadcast on the `potteryCreated` channel
const firedPottery = firePottery(data.piece, 2100)
// Broadcast on another channel with new data
radio.broadcast("potteryFired", { firedPottery })
})
export const firePottery = (piece, temperature) => {
piece.fired = true
if (temperature >= 2200) {
piece.cracked = true
} else {
piece.cracked = false
}
return piece
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment