DEV Community

Discussion on: Function identity in JavaScript, or how to remove event listeners properly

Collapse
 
pranay_rauthu profile image
pranay rauthu

The second solution you mentioned is called event bubbling. check this article for in depth explanation.

Collapse
 
smotchkkiss profile image
Emanuel Tannert

I think you’re referring to the fact that some events “bubble up” the DOM (mouseenter, for example!), which means they can not only be observed on the source element where they occurred, but on any parent element, too. So you don’t have to register event listeners on every element that you want to catch the events on, because a single listener on a common parent element will catch them all.

If you still need to know which particular element the event originated from, you can look that up in event.target, a property of the event object that I used in the last paragraphs of my post, too. Afaik, the browser mechanism of propagating events up the DOM is called event bubbling, while the technique of catching events on a parent element is called event delegation. The benefits of event delegation are that fewer event listeners are needed and that you don't have to remove or register event listeners as the DOM nodes emitting the events are added or removed, as long as the parent element you're listening on stays the same.

My post, however, is not about event delegation–note how even in the last code example in my second solution, I’m still adding an event listener to every single element in the collection. It’s about an even more basic insight that I think comes maybe one or two steps before using event delegation: that event handlers can be designed in general terms to work on any element, because they are receiving the event.target as an argument.

I think this is quite basic stuff and I’m belaboring very elementary points in much detail here. If you work with event handling in JavaScript every day and know this stuff inside out, it may be hard to recognise the insight that enables us to go from the first to the second solution, because it's so little. I only started to think about it in so much detail because I tried to understand what my colleague was thinking and wanted to explain to them what was going on. Also, I agree that a logical next step to further improve the code from the second solution would certainly be to use event delegation. But I neither discussed event delegation in my post, nor did I use it in the solution I presented.