Good Code
The good version keeps the handler reference and returns a cleanup function, so the caller can detach the listener when the UI is removed.
Lesson 08
Pair event listeners with cleanup so repeated setup does not duplicate behavior.
function attachSaveShortcut(target, onSave) {
// A stable handler reference lets callers remove the listener later.
function handleKeydown(event) {
if ((event.ctrlKey || event.metaKey) && event.key === "s") {
event.preventDefault();
onSave();
}
}
target.addEventListener("keydown", handleKeydown);
return () => {
target.removeEventListener("keydown", handleKeydown);
};
}function attachSaveShortcut(target, onSave) {
// Anonymous listeners cannot be removed by the caller.
target.addEventListener("keydown", (event) => {
if ((event.ctrlKey || event.metaKey) && event.key === "s") {
event.preventDefault();
onSave();
}
});
}The good version keeps the handler reference and returns a cleanup function, so the caller can detach the listener when the UI is removed.
The bad version adds an anonymous listener and gives the caller no practical way to remove it, which can duplicate shortcuts after repeated setup.