This content originally appeared on Go Make Things and was authored by Go Make Things
One of the first things I teach my JavaScript students when learning about events is event delegation.
When you have multiple elements that all react to the same type of event, you can listen for that event on a parent element, and filter out elements that aren’t the ones you’re looking for. It’s easier to author, and better for performance (fewer listeners in the browser’s memory).
<button class="click-me">Click Me</button>
<button>Do NOT Click Me</button>
<button class="click-me">Click Me</button>
document.body.addEventListener('click', function (event) {
// Only run on .click-me elements
if (!event.target.matches('button.click-me')) return;
// Do stuff...
});
The other day, one of my students asked me…
Is there a number of event listeners that’s considered “too many”?
Not really!
I think the React model of “an individual listener on every single interactive element” is bad, but there’s not some magic “that’s too many” number I can give you.
Generally speaking, I think in terms of components or libraries: one event of each type within a specific component.
If I’m listening for click
events, I’ll do that once in a specific library. If only one element needs it, I attach directly to that element. If not, I delegate.
If other libraries or components also use a click
event, I let them manage that separately.
☀️🧠 Summer of Learning Sale! Join the Lean Web Club today and get 1 month free, plus 30% off for the first three months after that. Click here to join for free now!
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2024-07-04T14:30:00+00:00) How many event listeners is too many in JavaScript?. Retrieved from https://www.scien.cx/2024/07/04/how-many-event-listeners-is-too-many-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.