在函数内部定义监听函数

Defining listener function inside function

当我在函数外定义函数时,无法访问glide参数:

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', focusListener);
        slideLink && slideLink.addEventListener('focus', focusListener);
    }
};

const focusListener = (event) => {
    const activeIndex = glide._i;
    const buttonIndex = event.target.dataset.slideIndex;
    if (activeIndex !== parseInt(buttonIndex)) {
        glide.go(`=${buttonIndex}`);
    }
};

因此,我做了类似的事情:

export const setFocusListenersForKeyboardNavigation = (glide) => {
    const focusListener = (event) => {
        const activeIndex = glide._i;
        const buttonIndex = event.target.dataset.slideIndex;
        if (activeIndex !== parseInt(buttonIndex)) {
            glide.go(`=${buttonIndex}`);
        }
    };

    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', focusListener);
        slideLink && slideLink.addEventListener('focus', focusListener);
    }
};

我想知道这是技巧还是好的做法?有没有更方便的方法呢

有外面的功能更好。 主要是为了可读性和测试,但如果你的函数被调用很多次(例如数百次),每次都重新定义甚至会影响性能。

您可以向侦听器添加箭头函数,这将使用正确的参数调用 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}`);
    }
};