我正在使用Intersection Observer API来跟踪网页上多个元素的可见性。当一个元素变得可见时,callback()
应该执行一个函数。限制:对于每个元素,函数只能执行一次。
这是我当前对 Web 分析项目的实现:
const elements = document.querySelectorAll('[data-observable]');
const callback = str => { console.log(str); };
const observer = new IntersectionObserver(handleIntersection);
elements.forEach(obs => {
observer.observe(obs);
});
function handleIntersection(entries, observer){
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
// Call this function only once per element, without modifying entry object
callback('observer-' + entry.target.getAttribute('data-observable'));
}
});
}
我正在努力寻找一个不修改现有元素、IntersectionObserver 或 IntersectionObserverEntries 的解决方案。
通常我会使用闭包来确保一个函数只执行一次:
function once(func) {
let executed = false;
return function() {
if (!executed) {
executed = true;
return func.apply(this, arguments);
}
};
}
但在这种情况下,我很难应用该函数,因为 IntersectionObserver 使用了一个奇怪的回调迭代器逻辑,每次任何元素更改时都会执行该逻辑(而不是使用事件驱动模型)。
任何想法,如何实现一个不改变其他元素或对象的每个元素函数调用?