Consider the following examples:
const buttons = [...document.querySelectorAll("button")];
const fn = i => console.log(i);
window.addEventListener("click", ({target}) => {
const i = buttons.indexOf(target);
i && fn(i)
});
buttons.forEach((button, i) => button.onclick = () => fn(i))
<button>button</button>
<button>button</button>
<button>button</button>
<button>button</button>
<button>button</button>
<button>button</button>
In the first example, we apply just one listener, but it will get called even though the click is not on a button.
In the second example, we apply multiple listeners, but the function will get called only if the click happened on a button.
But both of them are using the same function fn
.
Those are very basic examples, but ideal to explain my question. If we can have unknown number of buttons, does it make any difference in performance than setting up just one listener to the window?