我正在使用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>
假设用户单击第一个按钮,然后单击第二个按钮。我们第一次正常调用无限滚动函数。在第二个按钮单击时,我们销毁第一个实例并重置无限滚动容器,从而销毁前一个实例。
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"));
但是,发生的情况是我在第二次单击按钮时收到重复的帖子。控制台的输出发生两次,即使我只调用一次函数。发生了什么事情?我怎样才能使无限滚动重置100%?
您两次订阅同一元素,请参阅此部分:
$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
函数的更多信息。