+ 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 } });
5 ответов
+ 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
+ 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
+ 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?
+ 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.
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?