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

问题描述 投票:1回答:1

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

<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%重置?

javascript jquery infinite-scroll
1个回答
2
投票

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

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

这意味着每次调用CreateInfiniteScroll时,load.infiniteScroll事件的事件处理程序都会添加到具有类.comments-container的div中。您可以在重新附加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函数here的信息。

© www.soinside.com 2019 - 2024. All rights reserved.