To develop a centralized event broadcasting service across components, you can use an Event Bus. It enables decoupled communication between components.
Simple Steps (JavaScript/Frontend):
1. Create an Event Bus (eventBus.js):
// eventBus.js
const eventBus = {
events: {},
on(event, callback) {
(this.events[event] ||= []).push(callback);
},
off(event, callback) {
this.events[event] = (this.events[event] || []).filter(cb => cb !== callback);
},
emit(event, data) {
(this.events[event] || []).forEach(cb => cb(data));
}
};
export default eventBus;
2. Use in Component A (to emit an event):
import eventBus from './eventBus';
eventBus.emit('user-logged-in', { username: 'Mahak' });
3. Use in Component B (to listen to an event):
import eventBus from './eventBus';
eventBus.on('user-logged-in', (data) => {
console.log('User logged in:', data.username);
});