I tried to have a title that match the context I want my answer for. I explain myself.
After writting thousand of javascript lines of code (with or without jquery) I finally asked myself if I'm doing it wrong. Mainly thanks to jQuery adding event/delegating to an element is very easy, but all the example are quiet "easy"; meaning it doesn't take into account that you have a page full of list, button, dynamic things...
So my questions, is: Once again for a complexe website, with hundred of dynamic pages, ajax navigation, millions of user...
- Is there any advantage (beside simplicity) to place a global listener (body or whatever) and let all events bubble up ? When I look at angular it seems they listen 'ng-click' globally, but I can missthink.
Contexte
<body>
<div>
<ul>
<li><span click="myFunc"></span></li>
</ul>
</div>
</body>
-
Sidenot: I'm using jQuery for presentation/simplicity, but it's global question about js
// Standard binding example
$('span').on('click', func)
vs
// Standard delegation example
$('ul').on('click', 'span', func)
vs
// Dispatcher for 'block'
$('ul').on('click', localDispatcher)
vs
// One (and only one) Global Listener for all click
$(body).on('click', globalDispatcher)
With this example, the 3 first one need to be placed manually, on a dedicated js for this page.
Vs
The last one is just a simple event listener, that will use click
attribute to dispatch and can be set just once and for all.
I find the last one very cool, because it remove all the hassle to manage click/selector/dom management. Also I don't have to .off
every listener when I change page (ajax navigation).
But I wonder about performance or maybe another problems I can think about (that's why I ask the question :D).
I really wonder how "big web startup" manage this kind of Javascript.
Thanks :)