🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this article, I show you how to implement a simple event bus in Javascript. EventBus is an extremely useful tool for decoupling the components of your apps.
An event bus implements the publisher/subscriber pattern. It can be used to decouple the components of an application so that a component can react to events fired from another component without them having direct dependencies with each other. They only need to know the event bus.
Every subscriber can subscribe to a specific event. A subscriber will be notified when the event it subscribes to is published on the event bus.
A publisher can publish events on the event bus when something happens.
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this article, and run it by pressing the Enter/Return key.
Event bus implementation
Subscribe
In this implementation, a subscriber is a simple listener function or a callback function. The function is called when the event of interest is published in the event bus.
this.addEventListener = function(eventName, listener) {
if (!eventTopics[eventName] || eventTopics[eventName].length < 1) {
eventTopics[eventName] = [];
}
eventTopics[eventName].push(listener);
};
Publisher
The publish function takes as arguments the event and the arguments for the subscribers.
If there are no subscribers for eventType, it just returns.
Otherwise, it iterates over the subscribers registered for eventType and calls each function, passing the provided arguments.
this.emitEventListeners = function(eventName, params) {
if (!eventTopics[eventName] || eventTopics[eventName].length < 1)
return;
eventTopics[eventName].forEach(function(listener) {
listener(!!params ? params : {});
});
}
Note that we are using forEach() function to iterate over subscribers.
Remove Subscriber
You can also remove subscriber that registered for a specific event type.
this.removeListener = function(eventName, listener) {
if (!eventTopics[eventName] || eventTopics[eventName].length < 1)
return;
// delete listener by event name
delete eventTopics[eventName];
};
this.getListener = function(eventName){
return eventTopics[eventName];
}
Usage
In this example, we are subscribing two callback functions to single event1 using addEventListener() function. When we publish some data using emitEventListeners() function should notify all the subscribers that are subscribed to "event1".
function test(){
var eventBus = new EventBus();
var data1 = "some data for event1";
var data2 = "some data for event2";
// add listener to event1
eventBus.addEventListener("event1", function(data){
console.log("listener1 listen event1 -> " + data);
});
// add listener to event1
eventBus.addEventListener("event1", function(data){
console.log("listener2 listen event1 -> " + data);
});
// add listener to event2
eventBus.addEventListener("event2", function(data){
console.log("listener1 listen event2 -> " + data);
});
// add listener to event2
eventBus.addEventListener("event2", function(data){
console.log("listener2 listen event2 -> " + data);
});
eventBus.emitEventListeners("event1", data1);
eventBus.emitEventListeners("event2", data2);
}
test();
Complete Code and Output
/**
* Create an Event Bus object which has the registration and publishing API.
* addEventListener and emitEventListeners functions
* lets the subscriber and publisher to subscribe and publish on events respectively.
*/
function EventBus() {
var eventTopics = {};
this.addEventListener = function(eventName, listener) {
if (!eventTopics[eventName] || eventTopics[eventName].length < 1) {
eventTopics[eventName] = [];
}
eventTopics[eventName].push(listener);
};
this.emitEventListeners = function(eventName, params) {
if (!eventTopics[eventName] || eventTopics[eventName].length < 1)
return;
eventTopics[eventName].forEach(function(listener) {
listener(!!params ? params : {});
});
}
this.removeListener = function(eventName, listener) {
if (!eventTopics[eventName] || eventTopics[eventName].length < 1)
return;
// delete listener by event name
delete eventTopics[eventName];
};
this.getListener = function(eventName){
return eventTopics[eventName];
}
} //END EventBus
function test(){
var eventBus = new EventBus();
var data1 = "some data for event1";
var data2 = "some data for event2";
// add listener to event1
eventBus.addEventListener("event1", function(data){
console.log("listener1 listen event1 -> " + data);
});
// add listener to event1
eventBus.addEventListener("event1", function(data){
console.log("listener2 listen event1 -> " + data);
});
// add listener to event2
eventBus.addEventListener("event2", function(data){
console.log("listener1 listen event2 -> " + data);
});
// add listener to event2
eventBus.addEventListener("event2", function(data){
console.log("listener2 listen event2 -> " + data);
});
eventBus.emitEventListeners("event1", data1);
eventBus.emitEventListeners("event2", data2);
}
test();
Output:
listener1 listen event1 -> some data for event1
listener2 listen event1 -> some data for event1
listener1 listen event2 -> some data for event2
listener2 listen event2 -> some data for event2
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment