The Ultimate Guide to DOM Events and Pub/Sub

Rehan Pinjari
5 min read5 days ago

--

The Ultimate Guide to DOM Events and Pub/Sub

Hey, devs! Have you ever wondered how that nice button you clicked suddenly changes the content on your screen? It’s all because of events, and silent messengers who keep your web applications running smoothly.

But how are these events handled? Buckle up, because we’re about going deep into the world of DOM Events and Pub/Sub, the two main approaches to event handling in JavaScript.

Have a BIG IDEA in mind? Let’s discuss what we can gain together.

Write at Gmail | LinkedIn

Events 101

Think your web application to be an exciting event.

Events are like echoes that go through the crowd, telling different events of the application (the partygoers) that something noteworthy happened (such as someone spiking the punchbowl with code!).

These events trigger specific behaviors, keeping things interesting and dynamic.

Two main approaches for handling these events are DOM Events and Pub/Sub. Let’s break them down.

DOM Events

DOM Events

DOM Events are similar to the designated events rumors.

They have an unbreakable connection with specific components in the Document Object Model (DOM), your web page’s blueprint.

Common event types include clicks, mouseovers, and keystrokes.

To keep an eye out for these events, we use the addEventListener function. Think about handing out walkie-talkies to specified persons (event listeners) at the events.

When a relevant event happens (such as someone screaming “Fire!”), the walkie-talkie pops, and the listener (a function) takes action.

Examples

Here are some of the common DOM events:

  • click - When a user clicks on an element.
  • mouseover - When the user hovers over an element.
  • keydown - When a user presses a key onto their keyboard.

Event Handling

Adding event listeners to DOM elements is simple.

You use addEventListener to define the event and the code to be executed when it happens. For example:

document.getElementById('myButton').addEventListener('click', function() {
alert('Button clicked!');
});

Pros:

  • Simple to use, perfect for simple UI interactions.
  • Built-in browser support, there is no need for additional libraries.

Cons:

  • Tight coupling: Using too much can result in messy code.
  • Limited scalability: Not suitable for complex component interaction.

Pub/Sub

Pub/Sub

Pub/Sub, which means Publish-Subscribe, uses a more structured approach. Instead of depending on DOM components, it uses a central message bus, similar to an events message board. Here is the summary:

  • Publishers: These are the event announcers who broadcast messages (events) via the messaging bus.
  • Subscribers: These are the visitors who registered to receive specific announcements (events). When a relevant interaction comes, subscribers get notified and can take action.

Real-World Use

Pub/Sub isn’t only for JavaScript events.

It is used in everyday uses such as message brokers (high-volume email delivery) and notifications in real-time (those annoying sales pop-ups).

Pros:

  • Decoupling: Maintains component separateness, making code clearer and easier to maintain (no more event rumor loops!).
  • Scalability: Handles complex interaction among multiple parts with ease.

Cons:

  • Overhead: Setting up the message bus is a little more complicated than setting up DOM events.
  • Potential for confusion: Too many messages might cause data overload (event overload?).

DOM Events vs. Pub/Sub

The million-dollar question is: which one should you use? Here’s the cheat sheet:

DOM Events vs. Pub/Sub

Overall, DOM events work somewhat better for simple interactions.

However, the advantages of decoupling and scalability often surpass this in bigger systems.

Code Time!

Simple DOM Event Handling

// Ensure the DOM is fully loaded before attaching the event listener
document.addEventListener('DOMContentLoaded', function() {
// Get the button element by its ID
const button = document.getElementById('myButton');

// Check if the button element exists before attaching the event listener
if (button) {
button.addEventListener('click', function() {
console.log('Button clicked!');
});
} else {
console.error('Button element with ID "myButton" not found.');
}
});

Simple Pub/Sub Implementation

// Pub/Sub Module
const PubSub = (function() {
const events = {};

function subscribe(event, callback) {
if (typeof callback !== 'function') {
throw new Error('Callback must be a function');
}
if (!events[event]) {
events[event] = [];
}
// Prevent duplicate subscriptions
if (!events[event].includes(callback)) {
events[event].push(callback);
}
}

function publish(event, data) {
if (events[event]) {
events[event].forEach(callback => callback(data));
}
}

function unsubscribe(event, callback) {
if (events[event]) {
events[event] = events[event].filter(cb => cb !== callback);
}
}

return {
subscribe,
publish,
unsubscribe
};
})();

// Usage
PubSub.subscribe('buttonClicked', function(data) {
console.log('Button clicked with data:', data);
});

// Simulating a button click event
PubSub.publish('buttonClicked', { buttonId: 'myButton' });

// Example of unsubscribing
const callback = function(data) {
console.log('Another button click handler:', data);
};
PubSub.subscribe('buttonClicked', callback);
PubSub.unsubscribe('buttonClicked', callback);

Best Practices

DOM Events

  • Use meaningful event listener names for better readability (for example, button.addEventListener(‘click’, handleButtonClick)).
  • Remove event listeners when things are no longer needed to reduce memory leaks (such as cleaning up after events!).

Pub/Sub

  • Set detailed naming standards for events to avoid confusion.
  • Try using libraries such as EventEmitter to create a more robust and feature-rich pub/sub implementation.

When to Choose What

Suppose that you’re creating a website. Here’s an overview to help you pick your event-handling winner:

When to Choose DOM Events and Pub/Sub

Remember: There is no one-size-fits-all solution. In advanced applications, you can probably mix both approaches!

Final Words

So there you have it. DOM Events and Pub/Sub are two strong JavaScript event-handling approaches.

Experiment with each to see which one best meets your needs.

Don’t be afraid to be creative! Remember that advanced Pub/Sub libraries, such as Socket.IO, might offer extra features for real-time communication and wide event handling.

If you like this, please think about buying me a coffee! ☕️.

--

--