JavaScript

Lesson 08

Event listener cleanup

Pair event listeners with cleanup so repeated setup does not duplicate behavior.

Good Code

keyboard-shortcut.js
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);
  };
}

Bad Code

keyboard-shortcut.js
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();
    }
  });
}

Review Notes

What to review

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.

Bad Code

The bad version adds an anonymous listener and gives the caller no practical way to remove it, which can duplicate shortcuts after repeated setup.

Takeaways

  • Keep a stable handler reference and return a cleanup function when attaching listeners.