无限滚动触发事件太多次

时间:2021-04-23 08:20:44

标签: javascript laravel

我正在尝试使用 javascript 和 laravel 开发 infinet 滚动,但我发现滚动到达末尾时的 javascript 函数被多次触发,这使其无法正常工作。

javascript 代码是这样的:

<script type="text/javascript">
        window.onscroll = function(ev) {
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
                window.livewire.emit('load-more');
                console.log('load more');
            }
        };
   </script>

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:2)

您需要添加一个用于禁用加载的标志。这里我们向 window 对象添加一个布尔值 isLoading

<script type="text/javascript">
    window.isLoading = false

    window.onscroll = ev => {
      // Check scroll position
      if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // Check loading flag
        if(window.isLoading){
          console.log('still loading');
          return true
        }
        
        // Load more data
        window.livewire.emit('load-more');
        console.log('load more');

        // Set the flag to disable loading
        window.isLoading = true;
      }
    };
    
    // To reset the isLoading flag we'll emit an event from the Livewire component to the browser
    window.addEventListener('loading-complete', event => {
      console.log('loading complete');
      window.isLoading = false;
    })
</script>

如上所示,我们通过 emitting an event to the browser from the Livewire component (see the docs) 重置了 isLoading 标志:

public function loadData()
{
    // Load data

    // Dispatch event to frontend
    $this->dispatchBrowserEvent('loading-complete');
}