Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/__tests__/observe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,32 @@ test("should be able to use observe", () => {
);
});

test("should only clean up each observer callback once", () => {
const element = document.createElement("div");
const firstCallback = vi.fn();
const secondCallback = vi.fn();
const firstCleanup = observe(element, firstCallback, { threshold: 0.1 });
const secondCleanup = observe(element, secondCallback, { threshold: 0.1 });
const observer = intersectionMockInstance(element);

firstCleanup();
firstCleanup();
mockIsIntersecting(element, true);

expect(firstCallback).not.toHaveBeenCalled();
expect(secondCallback).toHaveBeenCalledTimes(1);
expect(observer.unobserve).not.toHaveBeenCalled();

secondCleanup();
expect(observer.unobserve).toHaveBeenCalledTimes(1);
expect(observer.unobserve).toHaveBeenCalledWith(element);
expect(observer.disconnect).toHaveBeenCalledTimes(1);

secondCleanup();
expect(observer.unobserve).toHaveBeenCalledTimes(1);
expect(observer.disconnect).toHaveBeenCalledTimes(1);
});

test("should convert options to id", () => {
expect(
optionsToId({
Expand Down
4 changes: 4 additions & 0 deletions src/observe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,11 @@ export function observe(
callbacks.push(callback);
observer.observe(element);

let unobserved = false;
return function unobserve() {
if (unobserved) return;
unobserved = true;

// Remove the callback from the callback list
callbacks.splice(callbacks.indexOf(callback), 1);

Expand Down
Loading