Most of the time β€”apart from simple todo applicationsβ€”, when you are writing a modern web application, you have to separate code into different modules to keep things manageable.

This makes it easy to separate the different behaviors of your application, as well as make it more easily scalable, not to mention readability.

But what happens when you have to achieve communication between two separate components? That’s where custom event publishing comes into place. It provides a similar behavior to the PubSub design pattern.

What Are Events?

So what exactly are events? As you may already know, JavaScript is event-driven, which means that the flow of the application is usually determined by events, such as various user interactions (clicks, keyboard input, scrolling, etc.)

There are tons of events you can attach to. Mouse alone has 15 different events you can listen to.

How do they work?

Events can be handled in two different ways. They are called event bubbling and capturing.

By default, events are using the bubbling model. When you attach an event to an element using addEventListener, the event is first captured in the innermost element and then propagates up to the root of the document.

const ul = document.getElementById('ul');

// By default, addEventListener uses the bubbling model
ul.addEventListener('click', () => console.log('πŸ‘¨'));
event-propagation-model.js

The exact opposite happens during the capturing phase; The event is first captured in the outermost element and propagates to inner elements.

These two different propagation models can help us decide, which element should receive the event first, given that the same event is registered for both a child and parent element.

// To use event capturing for capturing events
// on parents first, pass true as the 3rd parameter 
// to addEventListener

const ul = document.getElementById('parent');
const li = document.getElementById('child'); 

ul.addEventListener('click', () => console.log('πŸ‘¨'), true);
li.addEventListener('click', () => console.log('πŸ‘Ά'), true);

// Instead of seeing πŸ‘Ά, πŸ‘¨ in the console
// You'll see πŸ‘¨, πŸ‘Ά as the direction is changed with `true`
event-propagation-model.js

To experiment with the two propagation models, take a look at this Codepen example:

Overall, there are almost 200 different standard events you can listen to. Yet, there could be times when you need a custom event thrown by your application. This is where custom events can be super useful.

#javascript #developer

How to Make Custom Event Listeners in JavaScript
2.00 GEEK