From 1967de1f1da5d97b97aa5f829a40c2b37bf78ed5 Mon Sep 17 00:00:00 2001 From: Cotes Chung <11371340+cotes2020@users.noreply.github.com> Date: Sun, 9 Apr 2023 20:44:55 +0800 Subject: [PATCH] refactor(js): reduce function complexity --- .../modules/components/topbar-switcher.js | 54 ++++++++++--------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/_javascript/modules/components/topbar-switcher.js b/_javascript/modules/components/topbar-switcher.js index f3eebb7..1b0d025 100644 --- a/_javascript/modules/components/topbar-switcher.js +++ b/_javascript/modules/components/topbar-switcher.js @@ -6,7 +6,6 @@ import ScrollHelper from './utils/scroll-helper'; const $searchInput = $('#search-input'); const delta = ScrollHelper.getTopbarHeight(); -let didScroll; let lastScrollTop = 0; function hasScrolled() { @@ -60,34 +59,41 @@ function handleLandscape() { export function switchTopbar() { const orientation = screen.orientation; - if (orientation) { - orientation.onchange = () => { - const type = orientation.type; - if (type === 'landscape-primary' || type === 'landscape-secondary') { - handleLandscape(); - } - }; - } else { - // for the browsers that not support `window.screen.orientation` API - $(window).on('orientationchange', () => { - if ($(window).width() < $(window).height()) { - // before rotating, it is still in portrait mode. - handleLandscape(); - } - }); - } + let didScroll = false; - $(window).on('scroll', () => { - if (didScroll) { - return; + const handleOrientationChange = () => { + const type = orientation.type; + if (type === 'landscape-primary' || type === 'landscape-secondary') { + handleLandscape(); } - didScroll = true; - }); + }; - setInterval(() => { + const handleWindowChange = () => { + if ($(window).width() < $(window).height()) { + // before rotating, it is still in portrait mode. + handleLandscape(); + } + }; + + const handleScroll = () => { + didScroll = true; + }; + + const checkScroll = () => { if (didScroll) { hasScrolled(); didScroll = false; } - }, 250); + }; + + if (orientation) { + orientation.addEventListener('change', handleOrientationChange); + } else { + // for the browsers that not support `window.screen.orientation` API + $(window).on('orientationchange', handleWindowChange); + } + + $(window).on('scroll', handleScroll); + + setInterval(checkScroll, 250); }