How to develop a service that handles centralized event broadcasting across components

0 votes
Can i know How to develop a service that handles centralized event broadcasting across components?
6 days ago in Node-js by Nidhi
• 15,620 points
46 views

1 answer to this question.

0 votes

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);

});

answered 3 days ago by anonymous

Related Questions In Node-js

0 votes
0 answers
0 votes
1 answer

How to implement a service that provides real-time data synchronization across tabs?

To implement real-time data synchronization across browser ...READ MORE

answered 3 days ago in Node-js by anonymous
49 views
0 votes
1 answer

How do I add a custom script to my package.json file that runs a javascript file?

run npm run script1 it works for me READ MORE

answered Jan 10, 2023 in Node-js by Harisudarsan

edited Mar 5 42,076 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to design a pipe that accepts configuration options for flexible transformations?

Angular Pipe Implementation import { Pipe, PipeTransform } ...READ MORE

answered 3 days ago in Node-js by anonymous
31 views
0 votes
1 answer
0 votes
1 answer

How do services help in implementing the Facade Pattern in Angular applications?

In Angular, services help implement the Facade ...READ MORE

answered 3 days ago in Node-js by anonymous
46 views
0 votes
1 answer

How to develop a directive that restricts user input based on custom conditions?

To create an Angular directive that restricts ...READ MORE

answered Apr 10 in Node-js by anonymous
48 views
0 votes
1 answer

How to create a service that manages user sessions and authentication tokens?

1. Create the Auth Service (auth.service.ts) import { ...READ MORE

answered 3 days ago in Node-js by anonymous
36 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP