我正在使用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%重置?
您正在订阅两次相同的元素,请参阅此部分:
$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的信息。