猿问

在函数内部定义监听函数

当我在函数外部定义函数时,无法访问 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);

    }

};

我想知道这是黑客还是好的做法?有没有更方便的方法来做到这一点。


四季花海
浏览 116回答 1
1回答

慕田峪7331174

将功能放在外面更好。主要是为了可读性和测试,但如果您的函数被调用很多次(例如数百次),那么每次重新定义甚至可能会影响性能。您可以向侦听器添加箭头函数,它将使用正确的参数调用 focusListener。你可以这样做:export const setFocusListenersForKeyboardNavigation = (glide) => {&nbsp; &nbsp; const slides = glide._c.Html.slides;&nbsp; &nbsp; for (let i = 0; i < slides.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; const currentSlide = slides[i];&nbsp; &nbsp; &nbsp; &nbsp; const slideButton = currentSlide.querySelector(".js-slide-button");&nbsp; &nbsp; &nbsp; &nbsp; const slideLink = currentSlide.querySelector(".js-slide-link");&nbsp; &nbsp; &nbsp; &nbsp; slideButton && slideButton.addEventListener('focus', (event) => {focusListener(event, glide)});&nbsp; &nbsp; &nbsp; &nbsp; slideLink && slideLink.addEventListener('focus', (event) => {focusListener(event, glide));&nbsp; &nbsp; }};const focusListener = (event, glide) => {&nbsp; &nbsp; const activeIndex = glide._i;&nbsp; &nbsp; const buttonIndex = event.target.dataset.slideIndex;&nbsp; &nbsp; if (activeIndex !== parseInt(buttonIndex)) {&nbsp; &nbsp; &nbsp; &nbsp; glide.go(`=${buttonIndex}`);&nbsp; &nbsp; }};
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答