Today I Learned - Rocky Kev

TIL Grouping Event Handlers

POSTED ON:

TAGS:

Creating a single event handler object!

I'm super guilty of tying the click events like this...


const button1 = document.querySelector('button1');
const button2 = document.querySelector('button2');
const button3 = document.querySelector('button3');

button1.addEventListener('click', event => {
button.textContent = `Click count: ${event.detail}`;
});

button2.addEventListener('click', event => {
button.textContent = `Click count: ${event.detail}`;
});

button3.addEventListener('click', event => {
button.textContent = `Click count: ${event.detail}`;
});

A better method would be to group them together.

Something like below:

const button1 = document.querySelector('#button1');
const button2 = document.querySelector('#button2');
const button3 = document.querySelector('#button3');

// Use a single click event listener
document.addEventListener('click', event => {

// 1 - get the target
const element = event.target;

// 2 - business logic based on the target
if (element.tagName === 'BUTTON') {
document.querySelector(`#${element.id}Text`).textContent = `${element.id} Click count: ${event.detail}`;
}

});

See the Pen Untitled by rockykev (@rockykev) on CodePen.

That will allow me to keep ALL click events in one easy-to-read function rather than hunt it down.

Right now, the events are checked to see if it's a button and automatically assumes what happens based on the element id.

A better method would be to use data attributes.

Each handler name corresponds to the value of one of the data- attributes.

So something like:

<button data-click="logout">Log Out</button>

Now you can loop through data-click attributes to really control the flow!

If you want to go wild and crazy, check out this blog post.

NEXT LEVEL:
Strategies for working with data attributes in vanilla JavaScript


Related TILs

Tagged:

TIL not obsessively trying to be DRY

Quite often, DRY is applied to any duplication, rather than specifically to the duplication of business rules and knowledge. This is often made worse by automated code analysis tools, which will often highlight any duplication as a code smell.

TIL ways to organize eventListeners

Some code spaghetti I made recently was creating a lot of eventListeners for multiple buttons, and then forgot what they all connected to.

TIL Very Efficient Code

This is a great solution. Easy to understand. Executes really fast. No real-time string concatenation. No over-engineering. String appearance is easily customized.