Created
May 14, 2020 14:03
-
-
Save stevebrownlee/fbfa0e629db2eb4462ecd8de9fb517f0 to your computer and use it in GitHub Desktop.
Bare bones event broker
This file contains hidden or 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
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) | |
} | |
} | |
} |
This file contains hidden or 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
// 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