Callbacks
Callbacks are functions that we pass into other functions, which, in turn, will be invoked when they are needed. For example, in the client, if you want to listen to clicks on a specific DOM element, you attach an event handler via addEventListener
. The function you pass in is then called when clicks on that element occur:
const btnElement = document.querySelector<HTMLButtonElement>('.my-button'); function handleButtonClick(event: MouseEvent) { console.log('.my-button was clicked!'); } btnElement.addEventListener('click', handleButtonClick);
In this example, handleButtonClick
is a callback function given to addEventListener
. It will be called whenever someone clicks the .my-button
element.
Note
You can also inline the handleButtonClick
function, but you won't be able to call removeEventListener
later, which is required in certain cases, to avoid memory leaks.
On the server, callbacks are widely used...