繁体   English   中英

端点在无限滚动中被调用两次

[英]Endpoint being called twice in Infinite scroll

我正在使用Meta Fizzy无限滚动将指定的容器用作无限滚动容器。 我有两个按钮,一个按钮的端点不同于第二个按钮。 单击其中一个按钮时,将填充无限滚动容器。

<button data-api="/api/comments/1">First button</button>
<button data-api="/api/comments/2">Second button</button>

<div class="comments-container"></div>

假设用户单击第一个按钮,然后再单击第二个按钮。 第一次,我们正常调用infinitescroll函数。 在第二个按钮上单击,我们销毁第一个实例,并以销毁先前实例的方式重置无限滚动容器。

    function CreateInfiniteScroll(endPoint) {

        let $container = $(endPoint.getFeedContainer()).infiniteScroll({
            path: function () {
                return endPoint.getEndPoint();
            },
            // load response as flat text
            responseType: 'text',
            status: '.scroll-status',
            history: false,
        });


        $container.on('load.infiniteScroll', function (event, response) {
            let data = JSON.parse(response);
            console.log(data);
     }
  }

当单击第二个按钮时,我运行以下代码:

                $(".comments-container").infiniteScroll('destroy');
                $(".comments-container").removeData('infiniteScroll');
CreateInfiniteScroll(new EndPoints(buttonEndpoint, ".comments-container"));

但是,发生的是,第二次单击按钮后,我得到了重复的帖子。 即使我只调用一次函数,控制台的输出也会发生两次。 怎么了? 如何使infiniteScroll重设100%?

您要订阅两次相同的元素,请参阅此部分:

$container.on('load.infiniteScroll', function (event, response) {
  let data = JSON.parse(response);
  console.log(data);
});

这意味着每次调用CreateInfiniteScroll ,都会将load.infiniteScroll事件的事件处理程序添加到带有.comments-container类的div .comments-container 您可以在重新连接新的事件处理程序之前删除其他事件处理程序,例如在CreateInfiniteScroll函数中:

$container.off('load.infiniteScroll'); // Remove all event handlers first
$container.on('load.infiniteScroll', function (event, response) {
  let data = JSON.parse(response);
  console.log(data);
});

或者,您可以将其添加到按钮单击代码中:

// Clean up
$(".comments-container").infiniteScroll('destroy');
$(".comments-container").removeData('infiniteScroll');
$(".comments-container").off('load.infiniteScroll'); // remove all other events handlers

// Reinstantiate infinite scroll
CreateInfiniteScroll(new EndPoints(buttonEndpoint, ".comments-container"));

在此处阅读有关JQuery的.off函数的更多信息。

暂无
暂无

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

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