(
element: Element,
callback: ObserverInstanceCallback,
options: IntersectionObserverInit = {},
fallbackInView = unsupportedValue,
)
| 116 | * @return Function - Cleanup function that should be triggered to unregister the observer |
| 117 | */ |
| 118 | export function observe( |
| 119 | element: Element, |
| 120 | callback: ObserverInstanceCallback, |
| 121 | options: IntersectionObserverInit = {}, |
| 122 | fallbackInView = unsupportedValue, |
| 123 | ) { |
| 124 | if ( |
| 125 | typeof window.IntersectionObserver === "undefined" && |
| 126 | fallbackInView !== undefined |
| 127 | ) { |
| 128 | const bounds = element.getBoundingClientRect(); |
| 129 | callback(fallbackInView, { |
| 130 | isIntersecting: fallbackInView, |
| 131 | target: element, |
| 132 | intersectionRatio: |
| 133 | typeof options.threshold === "number" ? options.threshold : 0, |
| 134 | time: 0, |
| 135 | boundingClientRect: bounds, |
| 136 | intersectionRect: bounds, |
| 137 | rootBounds: bounds, |
| 138 | }); |
| 139 | return () => { |
| 140 | // Nothing to cleanup |
| 141 | }; |
| 142 | } |
| 143 | // An observer with the same options can be reused, so lets use this fact |
| 144 | const { id, observer, elements } = createObserver(options); |
| 145 | |
| 146 | // Register the callback listener for this element |
| 147 | const callbacks = elements.get(element) || []; |
| 148 | if (!elements.has(element)) { |
| 149 | elements.set(element, callbacks); |
| 150 | } |
| 151 | |
| 152 | callbacks.push(callback); |
| 153 | observer.observe(element); |
| 154 | |
| 155 | return function unobserve() { |
| 156 | // Remove the callback from the callback list |
| 157 | callbacks.splice(callbacks.indexOf(callback), 1); |
| 158 | |
| 159 | if (callbacks.length === 0) { |
| 160 | // No more callback exists for element, so destroy it |
| 161 | elements.delete(element); |
| 162 | observer.unobserve(element); |
| 163 | } |
| 164 | |
| 165 | if (elements.size === 0) { |
| 166 | // No more elements are being observer by this instance, so destroy it |
| 167 | observer.disconnect(); |
| 168 | observerMap.delete(id); |
| 169 | } |
| 170 | }; |
| 171 | } |
no test coverage detected
searching dependent graphs…