Why Custom Events Beat Callbacks in Web Components
Chris Ferdinandi’s latest piece digs into a common pain point: hooking into Web Components. His key insight is that custom events are a superior mechanism to callback functions, and he carefully lays out the reasoning.
With a typical JavaScript library, you pass callbacks in as part of the instantiate process. […] Because Web Components self-instantiate, though, there’s no easy way to do that.
The core issue is that callbacks are possible, just awkward in practice. Because components create themselves, developers never get a clean instantiation moment where they could hand off a function.
JavaScript provides developers with a way to emit custom events that developers can listen for with the
Element.addEventListener()method.
Custom events flip the model: Your component announces what happened, and outside code opts in to listen. The approach scales because it promotes loose coupling—a component doesn’t need to know which callbacks exist, only that it fires when the right thing occurs.
Ferdinandi also covers canceling such events, a subtle but powerful feature.



