Ad/iklan :







Search.Pencarian Menu

Add text send email to rh3252705.adda@blogger.com or Click this (Text porn Will delete) | Tambah teks kirim email ke rh3252705.adda@blogger.com atau Klik ini (Teks porno akan dihapus)
Total post.pos : 13631+

[Go Make Things] How many event listeners is too many in JavaScript?

☀️🧠 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!

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.

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+
0 Komentar untuk "[Go Make Things] How many event listeners is too many in JavaScript?"

Back To Top