]> git.ardis.lu - minimal-routing/commitdiff
Use one global click handler instead of individual handlers
authorArdis Lu <ardisglu@gmail.com>
Thu, 28 Nov 2024 06:23:00 +0000 (22:23 -0800)
committerArdis Lu <ardisglu@gmail.com>
Thu, 28 Nov 2024 06:23:00 +0000 (22:23 -0800)
This pattern allows downstream code to more easily override the handler with stopPropagation

index.html

index f1ecd46c12ff698419c3cfb089ab950f406b774c..615c9f3998ccfb13ad4c5a545aecad69ab84ea24 100644 (file)
   </main>
 
   <script>
-    const routers = document.querySelectorAll('[data-router]');
+    const routers = Array.from(document.querySelectorAll('[data-router]')); // Put into array to use .includes
     const content = document.querySelector('section');
     const pages = document.querySelectorAll('[data-page]');
 
     }
 
     // Set event handlers
-    for (const router of routers) {
-      router.addEventListener('click', e => {
-        if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
-          return; // Use default behavior if any keyboard modifier is applied to the click
-        }
+    addEventListener('click', e => {
+      if (!routers.includes(e.target)) {
+        return;
+      }
+      if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
+        return; // Use default behavior if any keyboard modifier is applied to the click
+      }
 
-        e.preventDefault();
-        route(e.target.dataset.route);
-      });
-    }
+      e.preventDefault();
+      route(e.target.dataset.route);
+    });
     addEventListener('popstate', _ => showPage(location.pathname.substring(1)));
 
     // Show the current URL (to support direct linking aka deep links)
This page took 0.04015 seconds and 4 git commands to generate.