Para mí, tiene sentido que se prefiera IntersectionObserver a agregar detectores de eventos basados en desplazamiento en estos días. Excelente.
Sin embargo, leí aquí y aquí que un Proxy ofrece una forma más deseable de hacer esto y que Object.observe es quizás incluso obsoleto.
Después de leer acerca de las trampas Proxy por un tiempo, todavía no puedo entender cómo las usaría en mi caso de uso imaginario a continuación, o encontrar buenas referencias para ello.
El caso de uso imaginario:
div s con colores de fondo aleatorios.div obtiene un IntersectionObserver .isIntersecting == true para cualquiera de los div s, el color de fondo del body cambia al de div .¿Cómo comenzaría a pensar en implementar esto usando proxies?
Fiddle here . En realidad crea un efecto atractivo, aunque contradictorio.
let numberOfDivs = 5;
function createDiv(divNumber) {
// set the div's tag name, class name and a unique ID
let aDiv = document.createElement('div');
aDiv.className = 'my-divs';
aDiv.id = 'div' + divNumber;
// set a random hex bg colour for the div;
// drops a leading zero 1/16 of the time but it's not material to the example
aDiv.style.backgroundColor = '#' + Math.floor(Math.random()*16777215).toString(16);
// append the div to the body
document.body.appendChild(aDiv);
// set IntersectionObserver on the div
let observer = new IntersectionObserver(whatsIn, {threshold: 0.5});
observer.observe(aDiv);
}
// create the divs
for ( let i = 0; i < numberOfDivs; i++ ) {
let newDiv = createDiv(i);
}
// examine the IntersectionObserver output whenever isIntersecting changes
function whatsIn(payload) {
console.log("Is " + payload[0].target.id + " intersecting? " + payload[0].isIntersecting);
// change background color based on most recent isIntersecting == true
document.body.style.backgroundColor =
payload[0].isIntersecting
? payload[0].target.style.backgroundColor
: document.body.style.backgroundColor;
}