Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
let eventDispatcher = function() {
let replaying = false;
let events = [];
let subscribers = {};
let dispatchEvent = (ev) => {
if (!replaying) {
events.push(ev);
}
for (const sub of subscribers[ev.name]) {
sub(ev);
}
}
let subscribe = (eventName, f) => {
if(subscribers[eventName]) {
subscribers[eventName].push(f);
} else {
subscribers[eventName] = [f];
}
}
let replay = () => {
replaying = true;
let i = 1
for (const ev of events) {
setTimeout(() => dispatchEvent(ev), 1000 * i);
i++;
}
setTimeout(() => replaying = false, 1000 * events.length)
}
return {
dispatch: dispatchEvent,
subscribe: subscribe,
replay: replay
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment