Skip to content

Commit 1967de1

Browse files
committed
refactor(js): reduce function complexity
1 parent c283e77 commit 1967de1

File tree

1 file changed

+29
-23
lines changed

1 file changed

+29
-23
lines changed

_javascript/modules/components/topbar-switcher.js

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import ScrollHelper from './utils/scroll-helper';
66
const $searchInput = $('#search-input');
77
const delta = ScrollHelper.getTopbarHeight();
88

9-
let didScroll;
109
let lastScrollTop = 0;
1110

1211
function hasScrolled() {
@@ -60,34 +59,41 @@ function handleLandscape() {
6059

6160
export function switchTopbar() {
6261
const orientation = screen.orientation;
63-
if (orientation) {
64-
orientation.onchange = () => {
65-
const type = orientation.type;
66-
if (type === 'landscape-primary' || type === 'landscape-secondary') {
67-
handleLandscape();
68-
}
69-
};
70-
} else {
71-
// for the browsers that not support `window.screen.orientation` API
72-
$(window).on('orientationchange', () => {
73-
if ($(window).width() < $(window).height()) {
74-
// before rotating, it is still in portrait mode.
75-
handleLandscape();
76-
}
77-
});
78-
}
62+
let didScroll = false;
7963

80-
$(window).on('scroll', () => {
81-
if (didScroll) {
82-
return;
64+
const handleOrientationChange = () => {
65+
const type = orientation.type;
66+
if (type === 'landscape-primary' || type === 'landscape-secondary') {
67+
handleLandscape();
68+
}
69+
};
70+
71+
const handleWindowChange = () => {
72+
if ($(window).width() < $(window).height()) {
73+
// before rotating, it is still in portrait mode.
74+
handleLandscape();
8375
}
76+
};
77+
78+
const handleScroll = () => {
8479
didScroll = true;
85-
});
80+
};
8681

87-
setInterval(() => {
82+
const checkScroll = () => {
8883
if (didScroll) {
8984
hasScrolled();
9085
didScroll = false;
9186
}
92-
}, 250);
87+
};
88+
89+
if (orientation) {
90+
orientation.addEventListener('change', handleOrientationChange);
91+
} else {
92+
// for the browsers that not support `window.screen.orientation` API
93+
$(window).on('orientationchange', handleWindowChange);
94+
}
95+
96+
$(window).on('scroll', handleScroll);
97+
98+
setInterval(checkScroll, 250);
9399
}

0 commit comments

Comments
 (0)