DEV Community 👩‍💻👨‍💻

Discussion on: 😇 "Javascript Closure" I think you can get what it is finally after reading this

Collapse
peerreynders profile image
peerreynders
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" contents="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real world event listener accessing its closure</title>
    <style>
     main {
       max-width: 11ch;
       display: flex;
       flex-direction: column;
       align-items: stretch;
     }
    </style>
    <script type="module">

     // `isClicked` is part of `clickListener`'s closure;
     let isClicked = false;

     const buttons = document.querySelectorAll('.button');
     buttons[0].addEventListener('click', clickListener);
     buttons[1].addEventListener('click', simpleListener, { once: true });

     // ---

     function clickListener(event) {
       // accessing/mutating `isClicked` in the "enclosing" closure
       if (!isClicked) {
         isClicked = true;
         event.target.textContent = 'Thank You!';
         return;
       }

       alert(`That's quite alright, thank you!`);
       event.preventDefault();
       event.stopPropagation();
     }

     function simpleListener({ target }) {
       target.textContent = 'Thank You!';
       target.disabled = true;
     }

    </script>
  </head>
  <body>
    <main>
      <button class="button">Click Me</button>
      <button class="button">Me Too!</button>
    </main>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode