Here's an example of event delegation and when you would use it.
Here is an interactive jsbin of with-delegation.js
https://jsbin.com/pufide/8/edit?html,js,console,output
JSBin is in general a great resource for trying out front-end code without having to do a lot of setup!
All files share the same index.html
incorrect-approach.js
implements a list which 'selects' (highlights in red) on hover. However, it only works for the original list of items, not for newly added items through our form input, as we aren't explicitly setting up event handlers there.
no-delegation.js
is identical to incorrect-approach.js
except that now all items (the original list and those added from the form) have the correct event handler functionality. We accomplish this by creating a helper function to create a 'movieItem' that adds the event handlers to each item. We then call it in two places, when making the original list, and when adding fromt he form.
delegation.js
is like no-delegation.js
but (you guessed it!) we implement our logic with event-delegation. Instead of having a special movieItem function where we add the handlers to each movieItem, instead we register the event handlers on the moviesContainer, but delegate to the individual item. This way, both our original list elements and newly added ones 'share' the same handlers without needing to think about it when adding new elements to the list.