TIL Grouping Event Handlers
POSTED ON:
TAGS: cleancode event-handlers javascript
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: cleancode