Attaching a single event listener to body instead of multiple separate ones | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Attaching a single event listener to body instead of multiple separate ones

Let's say I have several buttons in page header, chat section, etc. What would be best performance wise, attaching one listener to the body and having a conditional like provided in the code below, or just add a separate listener to each button? --- document.body.addEventListener('click', function (event) { switch(event.target.id){ case "button_id1": function1(); break; case "button_id2": function2(); break; // etc } });

17th Apr 2023, 11:37 AM
Alex Snaidars
Alex Snaidars - avatar
5 Answers
+ 6
Alex Snaidars You are talking about observer pattern. Yes, it is a good way if you want multiple response from one action. https://www.dofactory.com/javascript/design-patterns/observer
17th Apr 2023, 1:23 PM
Bob_Li
Bob_Li - avatar
+ 7
Yeah it can be regarded as very good optimisation, Specifically switch-case used here will make the accessing of function bit fast I would say it's really good choice to use single event listener instead of multiple listener https://code.sololearn.com/WHbW47blHu4D/?ref=app
17th Apr 2023, 12:19 PM
I am offline
I am offline - avatar
+ 3
What if there are many buttons? wouldn't it make the `switch` body grow excessively? how was that from maintainability PoV? is it worth it?
17th Apr 2023, 6:25 PM
Ipang
+ 1
@Ipang, I guess it is not the point here, I bet there are several good solutions if the are lots of click elements instead of manually hard coding each element case. Thanks @Snehil and @Bob_Li for answers.
19th Apr 2023, 11:07 AM
Alex Snaidars
Alex Snaidars - avatar
0
@Alex What did you mean hard coding each element case? As I understand it, "hard coding" is a practice where a coder implements a static algorithm in their code. The algorithm solves the problem at hand, but it does so in one very specific way as it was written in the code. The algorithm does not adapt to differences of data. Maybe I misunderstood the term?
19th Apr 2023, 11:17 AM
Ipang