JavaScript and TypeScript course ยท Module 9: Design Patterns and Architecture
Event-driven architecture and time systems in JavaScript
In this lesson9
After mastering design patterns, SOLID principles, functional programming, and bundle optimization, it's time to combine this knowledge in practice. In this chapter, we will build an event-driven system with time simulation - a pattern commonly used in games, simulations, and monitoring systems.
What is event-driven architecture?
Event-driven architecture is an approach where program flow is controlled by events - user actions, sensor signals, time passage, or messages from other systems. Instead of linear code execution, the system reacts to events as they occur.
// Traditional approach - linear
function checkPark() {
checkFences();
feedDinosaurs();
updateVisitors();
generateReport();
}
// Event-driven - reactive
const eventBus = new EventEmitter();
eventBus.on('fence:alarm', handleFenceAlarm);
eventBus.on('dinosaur:hungry', scheduleFeedingRun);
eventBus.on('visitor:entered', updateVisitorCount);
eventBus.on('hour:changed', generateHourlyReport);In the event-driven approach, each component operates independently and reacts only to events that concern it. This leads to loose coupling - a goal that the SOLID principles you learned earlier also serve, especially Dependency Inversion.
The EventEmitter pattern
At the heart of event-driven architecture is EventEmitter - an implementation of the Observer pattern that we learned in the first lesson of this module.
class EventEmitter {
constructor() {
this.listeners = new Map();
}
on(event, callback) {
if (!this.listeners.has(event)) {
this.listeners.set(event, []);
}
this.listeners.get(event).push(callback);
return this; // Fluent interface
}
off(event, callback) {
if (!this.listeners.has(event)) return this;
const callbacks = this.listeners.get(event);
const index = callbacks.indexOf(callback);
if (index > -1) callbacks.splice(index, 1);
return this;
}
emit(event, ...args) {
if (!this.listeners.has(event)) return false;
// Copy the array, because once() removes a listener during the loop
[...this.listeners.get(event)].forEach(callback => {
callback(...args);
});
return true;
}
once(event, callback) {
const wrapper = (...args) => {
this.off(event, wrapper); // unregister first, then call
callback(...args);
};
return this.on(event, wrapper);
}
}The once method is an elegant example of the Decorator pattern - it wraps the original callback in a wrapper that automatically unregisters itself after the first invocation.
Time simulation - day/night cycle
In simulation systems, time is a key element. In Jurassic Park, the day/night cycle affects dinosaur behavior, feeding schedules, visiting hours, and security protocols.
class TimeSimulation extends EventEmitter {
constructor() {
super();
this.currentHour = 6; // Start at 6:00
this.day = 1;
this.scheduledEvents = [];
this.isRunning = false;
}
advanceHour() {
this.currentHour++;
if (this.currentHour >= 24) {
this.currentHour = 0;
this.day++;
this.emit('day:changed', this.day);
}
this.emit('hour:changed', this.currentHour, this.day);
// Check scheduled events
this.checkScheduledEvents();
// Emit only when the time of day changes
const timeOfDay = this.getTimeOfDay();
if (timeOfDay !== this.timeOfDay) {
this.timeOfDay = timeOfDay;
this.emit('timeOfDay:changed', timeOfDay);
}
}
getTimeOfDay() {
if (this.currentHour >= 6 && this.currentHour < 12) return 'morning';
if (this.currentHour >= 12 && this.currentHour < 18) return 'day';
if (this.currentHour >= 18 && this.currentHour < 22) return 'evening';
return 'night';
}
scheduleEvent(hour, callback, options = {}) {
const event = {
hour,
callback,
recurring: options.recurring || false,
label: options.label || 'unnamed'
};
this.scheduledEvents.push(event);
return event;
}
checkScheduledEvents() {
this.scheduledEvents = this.scheduledEvents.filter(event => {
if (event.hour === this.currentHour) {
event.callback(this.currentHour, this.day);
return event.recurring; // Keep only recurring ones
}
return true;
});
}
}Notice how the TimeSimulation class inherits from EventEmitter - this is an application of the Open/Closed principle from SOLID. We can extend simulation behavior by adding new listeners without modifying the class itself.
Scheduling recurring events
In a real system, many events repeat cyclically - feeding dinosaurs, security patrols, status reports.
const sim = new TimeSimulation();
// Feeding carnivores - daily at 7:00 and 17:00
sim.scheduleEvent(7, (hour, day) => {
console.log(`Day ${day}, ${hour}:00 - Feeding carnivores`);
}, { recurring: true, label: 'feeding-carnivores' });
sim.scheduleEvent(17, (hour, day) => {
console.log(`Day ${day}, ${hour}:00 - Second feeding for carnivores`);
}, { recurring: true, label: 'feeding-carnivores-2' });
// Security patrols - every hour at night (22:00-5:00)
for (const h of [22, 23, 0, 1, 2, 3, 4, 5]) {
sim.scheduleEvent(h, (hour, day) => {
console.log(`Day ${day}, ${hour}:00 - Night patrol`);
}, { recurring: true, label: `patrol-${h}` });
}
// Daily report - at 8:00
sim.scheduleEvent(8, (hour, day) => {
console.log(`Day ${day} - Generating daily report`);
}, { recurring: true, label: 'daily-report' });Reacting to times of day
Event-driven architecture allows different subsystems to react independently to the same change:
// Lighting system
sim.on('timeOfDay:changed', (timeOfDay) => {
const lightingProfiles = {
morning: { brightness: 70, color: 'warm-white' },
day: { brightness: 100, color: 'daylight' },
evening: { brightness: 40, color: 'amber' },
night: { brightness: 10, color: 'red' } // Red so as not to startle dinosaurs
};
const profile = lightingProfiles[timeOfDay];
console.log(`Lighting: ${profile.brightness}% (${profile.color})`);
});
// Security system
sim.on('timeOfDay:changed', (timeOfDay) => {
if (timeOfDay === 'night') {
console.log('Activating night security protocols');
console.log('Increasing fence voltage by 20%');
console.log('Enabling thermal cameras');
} else if (timeOfDay === 'morning') {
console.log('Deactivating night protocols');
console.log('Restoring standard fence voltage');
}
});
// Visitor system
sim.on('hour:changed', (hour) => {
if (hour === 9) console.log('Park open for visitors');
if (hour === 18) console.log('Last visitor admission');
if (hour === 20) console.log('Park closed - guest evacuation');
});Combining with functional programming
Event-driven architecture can be enriched with functional techniques we learned earlier in the module:
// Pure functions for data transformation
const calculateFeedingAmount = (species, weight, hour) => {
const baseAmount = weight * 0.02; // 2% of body mass
const timeMultiplier = hour < 12 ? 1.2 : 0.8; // More in the morning
return Math.round(baseAmount * timeMultiplier);
};
// Function composition for event processing
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const processAlert = pipe(
(alert) => ({ ...alert, timestamp: Date.now() }),
(alert) => ({ ...alert, severity: alert.level > 7 ? 'critical' : 'warning' }),
(alert) => ({ ...alert, notified: true })
);
// Usage with event system
sim.on('alert:triggered', (rawAlert) => {
const processedAlert = processAlert(rawAlert);
console.log(`Alert [${processedAlert.severity}]: ${processedAlert.message}`);
});Managing simulation state
We combine the state management pattern (exercise_9_4) with the event system:
class SimulationState {
constructor(simulation) {
this.state = {
parkStatus: 'operational',
activeAlerts: 0,
dinosaursCount: 0,
visitorsCount: 0,
fencesStatus: 'all-operational'
};
this.history = [];
// React to simulation events
simulation.on('hour:changed', (hour) => {
this.updateState({ lastUpdate: hour });
});
simulation.on('alert:triggered', () => {
this.updateState({
activeAlerts: this.state.activeAlerts + 1
});
});
}
updateState(changes) {
// Immutability - new state object
const previousState = { ...this.state };
this.state = { ...this.state, ...changes };
this.history.push({
timestamp: Date.now(),
previous: previousState,
current: { ...this.state }
});
}
getState() {
return Object.freeze({ ...this.state });
}
}Testing event-driven systems
Event-driven systems are easy to test thanks to loose coupling of components:
// Time simulation test
function testTimeSimulation() {
const sim = new TimeSimulation();
const events = [];
sim.on('hour:changed', (hour) => events.push({ type: 'hour', hour }));
sim.on('day:changed', (day) => events.push({ type: 'day', day }));
// Simulate 25 hours (going through an entire day)
for (let i = 0; i < 25; i++) {
sim.advanceHour();
}
console.log(`Recorded events: ${events.length}`);
console.log(`Day changes: ${events.filter(e => e.type === 'day').length}`);
console.log(`Current day: ${sim.day}, hour: ${sim.currentHour}`);
}
testTimeSimulation();Summary
Event-driven architecture combines many patterns and principles that you learned in this module:
- Observer (exercise 9_1) - foundation of the event system
- SOLID (exercise 9_2) - loose coupling, openness to extensions
- Functional programming (exercise 9_3) - pure functions for event processing
- State management (exercise 9_4) - reactive state updates
- Optimization (exercise 9_5-9_7) - a small bundle and subsystems loaded only when they are needed
This is preparation for the final project, where you will integrate all these elements into a complete Jurassic Park management system.
Code for this lesson: index.js
// Time Simulation in the Park
// Exercise: Implement a day/night cycle simulation
class TimeSimulation {
constructor() {
this.currentHour = 6;
this.day = 1;
this.events = [];
this.isRunning = false;
}
// Implement the methods:
// advanceHour() - advance time by one hour
// scheduleEvent(hour, callback) - schedule an event
// getTimeOfDay() - return the time of day (morning/day/evening/night)
advanceHour() {
// Your code here
}
scheduleEvent(hour, callback) {
// Your code here
}
getTimeOfDay() {
// Your code here
}
}
const sim = new TimeSimulation();
console.log("Simulation: Day", sim.day, "Hour:", sim.currentHour);Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What characterizes event-driven architecture?
2. What three basic methods should an EventEmitter implement?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the elements of an EventEmitter.on call in the correct order:
- Code editor
The index.js file has the EventEmitter from the event-driven architecture lesson and a ParkTimeSystem class that simulates the hours in the park. Fill in the blanks: ___BLANK1___ is the array method that removes one listener at the found index in off(), ___BLANK2___ is the class that ParkTimeSystem extends to get the on, off and emit methods, and ___BLANK3___ is the array method that picks from the scheduled events only those for the current hour. Every hour advanceHour() emits 'hour:changed' with the hour and the day, after midnight first 'day:changed' with the day number, and every event scheduled with schedule(hour, name) for that hour emits 'event:triggered' with the name and the hour. start(intervalMs) starts a setInterval loop, and stop() stops it.
- Vertical ordering
Arrange the stages of building an event-driven system:
- Click in order
Arrange testing levels from lowest to highest.