【问题标题】:Endpoint being called twice in Infinite scroll端点在无限滚动中被调用两次
【发布时间】:2019-08-31 07:39:38
【问题描述】:

我正在使用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】:

    你订阅了同一个元素两次,看这个部分:

    $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

    【讨论】:

    • 只是一个简单的问题,似乎与此容器相关的所有事件处理程序现在都已关闭......例如,有一个与此容器相关的点击处理程序,我无法点击它跨度>
    • 您可以将要删除的特定事件处理程序传递给.off 函数。我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多