gpt4 book ai didi

javascript - 为什么我的 EventListener 被调用两次?

转载 作者:行者123 更新时间:2023-11-27 23:54:29 28 4
gpt4 key购买 nike

在我的 Angular 移动应用 ( Ionic framework ) 中,我正在设置无限滚动功能。它与仪表板版本的代码基本相同,但我的 scrollTagsPanel被调用两次。

获取标签工厂在我的里面getTagsFactory我执行 API 调用并检索返回标签对象,然后将标签传递到 getTagsColHeight tagsPanelDirective 内的函数:

tagsPanelCtrl.tagsPanel.totalTags = data.data.ticker_tags_rows;
tagsPanelCtrl.tagsPanel.tagsLoaded = true;
tagsPanelCtrl.tagsPanel.getTagsColHeight(tagsPanelCtrl.tagsPanel.tags);

tagsPanelDirective

这里是唯一负责无限滚动的两个方法。 getTagsColHeight检查以确保tags数组不为空,那么它只是添加事件 scroll到函数scrollTagsPanel .

计算判断标签列的高度tagsCol已达到与其高度相匹配的点 scrollTagsPanel .

function getTagsColHeight(tags) {
if (tags.length != 0 || tags.length != undefined) {
$timeout(function() {
tagsCol.addEventListener('scroll', scrollTagsPanel);
});
}
}

function scrollTagsPanel(event) {
// Reached bottom of tags panel:
console.log('tagsCol height: ', tagsCol.offsetHeight);
console.log('scrolled point: ',(tagsCol.scrollHeight - tagsCol.scrollTop));

if ((tagsCol.scrollHeight - tagsCol.scrollTop) === tagsCol.offsetHeight) {
if (!vm.limitReached) {

vm.start += vm.limit;
vm.tagsLoaded = false;

if ((vm.start + vm.limit) > vm.totalTags) {
vm.limitReached = true;
console.log('vm.limitReached = true!', vm.limitReached);
}

console.log('scrollTagsPanel...');
loadTags();
}
}
}

哪个滚动步骤会产生具有完全相同数据的 2 个调用:

enter image description here

console.log(event)我看到 1 Event {}和 1 CustomEvent {} ,这有帮助吗?

enter image description here

<小时/>

更新 - 好吧,如果我单击该列,我可以将事件首先调用一次,所以我猜它在滚动时同时检测到单击和滚动?

下面,我滚动一次,然后单击两次:

enter image description here

最佳答案

var timeout;

tagsCol.addEventListener('scroll', function () {
clearTimeout(timeout);
timeout = setTimeout(function() {
scrollTagsPanel();
}, 50);
});

根据:https://stackoverflow.com/a/22018607/636478

<小时/>

添加 AngularJS 版本:

tagsCol.addEventListener('scroll', function () {
$timeout.cancel(vm.scrollEventTimer);
clearTimeout(vm.scrollEventTimer);
vm.scrollEventTimer = $timeout(function() {
scrollTagsPanel();
}, 50);
});

关于javascript - 为什么我的 EventListener 被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32383804/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com