1 回答

TA貢獻1828條經(jīng)驗 獲得超13個贊
將功能放在外面更好。主要是為了可讀性和測試,但如果您的函數(shù)被調(diào)用很多次(例如數(shù)百次),那么每次重新定義甚至可能會影響性能。
您可以向偵聽器添加箭頭函數(shù),它將使用正確的參數(shù)調(diào)用 focusListener。你可以這樣做:
export const setFocusListenersForKeyboardNavigation = (glide) => {
const slides = glide._c.Html.slides;
for (let i = 0; i < slides.length; i++) {
const currentSlide = slides[i];
const slideButton = currentSlide.querySelector(".js-slide-button");
const slideLink = currentSlide.querySelector(".js-slide-link");
slideButton && slideButton.addEventListener('focus', (event) => {focusListener(event, glide)});
slideLink && slideLink.addEventListener('focus', (event) => {focusListener(event, glide));
}
};
const focusListener = (event, glide) => {
const activeIndex = glide._i;
const buttonIndex = event.target.dataset.slideIndex;
if (activeIndex !== parseInt(buttonIndex)) {
glide.go(`=${buttonIndex}`);
}
};
添加回答
舉報