为了账号安全,请及时绑定邮箱和手机立即绑定

在函数内部定义监听函数

在函数内部定义监听函数

四季花海 2023-06-29 15:36:40
当我在函数外部定义函数时,无法访问 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);    }};我想知道这是黑客还是好的做法?有没有更方便的方法来做到这一点。
查看完整描述

1 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

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


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

    }

};


查看完整回答
反对 回复 2023-06-29
  • 1 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信