From 801c362d49f08b4795edf6e06faf89120c611caa Mon Sep 17 00:00:00 2001 From: Kieran Boyle Date: Tue, 23 Mar 2021 11:28:12 -0700 Subject: [PATCH] support dynamically changing the rootMargin --- src/IntersectionObserver.svelte | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/IntersectionObserver.svelte b/src/IntersectionObserver.svelte index 778bdb6..b14853d 100644 --- a/src/IntersectionObserver.svelte +++ b/src/IntersectionObserver.svelte @@ -49,6 +49,7 @@ const dispatch = createEventDispatcher(); + let prevRootMargin = null; let prevElement = null; afterUpdate(async () => { @@ -58,7 +59,7 @@ if (entry.isIntersecting) { dispatch("intersect", entry); - if (once) observer.unobserve(entry.target); + if (once) observer.unobserve(element); } } @@ -70,13 +71,21 @@ if (prevElement !== null) observer.unobserve(prevElement); prevElement = element; } + + if (prevRootMargin && rootMargin !== prevRootMargin) { + observer.disconnect(); + prevElement = null; + initialize(); + } + + prevRootMargin = rootMargin; }); onDestroy(() => { if (observer) observer.disconnect(); }); - $: if (typeof window !== "undefined") { + const initialize = () => { observer = new IntersectionObserver( (entries) => { entries.forEach((_entry) => { @@ -87,6 +96,12 @@ { root, rootMargin, threshold } ); } + + $: { + if (typeof window !== "undefined") { + initialize(); + } + }