Skip to content

Commit 59a877f

Browse files
authored
Merge pull request #46 from oumoussa98/fix-observer
fix: fixed mulitple components on the same page
2 parents 45b57eb + db44803 commit 59a877f

File tree

2 files changed

+9
-13
lines changed

2 files changed

+9
-13
lines changed

src/components/InfiniteLoading.vue

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { onMounted, ref, toRefs, onUnmounted, watch, nextTick } from "vue";
44
55
import {
66
startObserver,
7-
stopObserver,
87
stateHandler,
98
initEmitter,
109
isVisible,
@@ -20,6 +19,7 @@ const props = defineProps({
2019
slots: { type: Object, required: false },
2120
});
2221
22+
let observer = null;
2323
const infiniteLoading = ref(null);
2424
const state = ref("ready");
2525
const { top, firstload, target, distance } = props;
@@ -44,24 +44,24 @@ const stateWatcher = () =>
4444
parentEl.scrollTop = parentEl.scrollHeight - prevHeight;
4545
if (newVal == "loaded" && isVisible(infiniteLoading.value, params.parentEl))
4646
params.emit();
47-
if (newVal == "complete") stopObserver();
47+
if (newVal == "complete") observer.disconnect();
4848
});
4949
5050
const identifierWatcher = () =>
5151
watch(identifier, () => {
5252
state.value = "ready";
53-
stopObserver();
54-
startObserver(params);
53+
observer.disconnect();
54+
observer = startObserver(params);
5555
});
5656
5757
onMounted(() => {
58-
startObserver(params);
58+
observer = startObserver(params);
5959
stateWatcher();
6060
if (identifier) identifierWatcher();
6161
});
6262
6363
onUnmounted(() => {
64-
stopObserver();
64+
observer.disconnect();
6565
});
6666
</script>
6767

src/utils.js

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,11 @@ const isVisible = (el, view) => {
2727
return elRect.top >= viewRect.top && elRect.bottom <= viewRect.bottom;
2828
};
2929

30-
let observer;
3130
const startObserver = params => {
3231
params.parentEl = document.querySelector(params.target) || null;
3332
let rootMargin = `0px 0px ${params.distance}px 0px`;
3433
if (params.top) rootMargin = `${params.distance}px 0px 0px 0px`;
35-
observer = new IntersectionObserver(
34+
const observer = new IntersectionObserver(
3635
entries => {
3736
const entry = entries[0];
3837
if (entry.isIntersecting) {
@@ -43,10 +42,7 @@ const startObserver = params => {
4342
{ root: params.parentEl, rootMargin }
4443
);
4544
observer.observe(params.infiniteLoading.value);
45+
return observer;
4646
};
4747

48-
const stopObserver = () => {
49-
observer.disconnect();
50-
};
51-
52-
export { startObserver, stopObserver, stateHandler, initEmitter, isVisible };
48+
export { startObserver, stateHandler, initEmitter, isVisible };

0 commit comments

Comments
 (0)