简体   繁体   English

如何重构此 Javascript 代码以使其更加模块化和简洁?

[英]How can I refactor this Javascript code to make it more modular and concise?

var vid1 = document.getElementById("v1");
var vid2 = document.getElementById("v2");
var vidArr = [vid1,vid2];

var tempListener1 = function checkViewA(){
    if(elementInView(vid1)){
        playVideo(vid1);
        window.removeEventListener('scroll', tempListener1); // so the video only plays once
    }
}

var tempListener2 = function checkViewB(){
    if(elementInView(vid2)){
        playVideo(vid2);
        window.removeEventListener('scroll', tempListener2);
    }
}

// scroll event listeners
window.addEventListener('scroll', tempListener1);
window.addEventListener('scroll', tempListener2); 

// this plays the video
async function playVideo(v){ 
    v.play();
}

I want to be able to keep adding videos that get played when they are in view without having to keep adding variables, event listeners.我希望能够继续添加在视图中播放的视频,而不必继续添加变量、事件侦听器。 In javascript you can't remove-listeners that have functions with parameters which is why I put those into variables.在 javascript 中,您无法删除具有带参数函数的侦听器,这就是我将它们放入变量的原因。 Any insights would be welcome.欢迎任何见解。

First get a collection of all videos elements in a Set, then add a single scroll listener.首先获取 Set 中所有视频元素的集合,然后添加单个滚动侦听器。 When the listener runs, iterate over the Set.当侦听器运行时,迭代 Set。 Whenever a video is found which is in view, play it and remove it from the Set:每当找到可见的视频时,播放它并将其从 Set 中删除:

const videos = new Set(document.querySelectorAll('video'));
window.addEventListener('scroll', () => {
  for (const video of videos) {
    if (elementInView(video)) {
      video.play();
      videos.delete(video);
    }
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM