Callbacks On Web Components? | CSS-Tricks


A gem from Chris Ferdinandi that details how to use custom events to hook into Web Components. More importantly, Chris dutifully explains why custom events are a better fit than, say, callback functions.

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.

There’s a way to use callback functions, just not an “easy” way to go about it.

JavaScript provides developers with a way to emit custom events that developers can listen for with the Element.addEventListener() method.

We can use custom events to let developers hook into the code that we write and run more code in response to when things happen. They provide a really flexible way to extend the functionality of a library or code base.

Don’t miss the nugget about canceling custom events!

Direct Link →

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here