Add and Remove Event Listeners while an Event is Dispatching

Alex Reardon
InstructorAlex Reardon

Share this video with your friends

Send Tweet
Published 6 months ago
Updated 5 months ago

What happens when you add an event listener to an event target while an event is in the process of being dispatched? Let's find out together!

Instructor: [0:00] It is possible for an event listener to add more event listeners to the event path while the event is being dispatched. This event listener would be able to add more event listeners along here. All of these event listeners would be executed, as they are on the subsequent event path.

[0:19] This event listener could add event listeners to its parent in the capture phase during an event, but these won't be executed. This event target in that phase has already finished, and so these event listeners won't be called as part of this event.

[0:32] Also, if this event listener adds more event listeners to the same event target in the same event phase during an event, then these added event listeners will not be executed as well. It also is possible for an event listener to remove upcoming event listeners on the event path.

[0:50] This event listener here could say, "I actually want to remove this event listener," and it could do that. This event listener, the removed one, would not be executed as part of the event path.

[1:02] A difference with removing upcoming event listeners during an event is that you can remove event listeners on the same event target in the same event phase. This event listener would be able to remove this event listener here, and then the removed event listener would not be called.

[1:21] The takeaway here is that the event listeners on the event path are not fixed at the point at which the event is dispatched. The event listeners that will be executed during dispatching of an event can be modified.

[1:35] At the time of recording, if a capture event listener on the target of an event adds a bubble event listener on the same event target, then some browsers will call the new bubble event listener, and others will not. Because of the inconsistencies, it is safest not to rely on this behavior.