You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.5 KiB
58 lines
1.5 KiB
8 years ago
|
// Wrapper for IntersectionObserver in order to make working with it
|
||
|
// a bit easier. We also follow this performance advice:
|
||
|
// "If you need to observe multiple elements, it is both possible and
|
||
|
// advised to observe multiple elements using the same IntersectionObserver
|
||
|
// instance by calling observe() multiple times."
|
||
|
// https://developers.google.com/web/updates/2016/04/intersectionobserver
|
||
|
|
||
|
class IntersectionObserverWrapper {
|
||
|
|
||
|
callbacks = {};
|
||
|
observerBacklog = [];
|
||
|
observer = null;
|
||
|
|
||
|
connect (options) {
|
||
|
const onIntersection = (entries) => {
|
||
|
entries.forEach(entry => {
|
||
|
const id = entry.target.getAttribute('data-id');
|
||
|
if (this.callbacks[id]) {
|
||
|
this.callbacks[id](entry);
|
||
|
}
|
||
|
});
|
||
|
};
|
||
|
|
||
|
this.observer = new IntersectionObserver(onIntersection, options);
|
||
|
this.observerBacklog.forEach(([ id, node, callback ]) => {
|
||
|
this.observe(id, node, callback);
|
||
|
});
|
||
|
this.observerBacklog = null;
|
||
|
}
|
||
|
|
||
|
observe (id, node, callback) {
|
||
|
if (!this.observer) {
|
||
|
this.observerBacklog.push([ id, node, callback ]);
|
||
|
} else {
|
||
|
this.callbacks[id] = callback;
|
||
|
this.observer.observe(node);
|
||
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
unobserve (id, node) {
|
||
|
if (this.observer) {
|
||
|
delete this.callbacks[id];
|
||
|
this.observer.unobserve(node);
|
||
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
disconnect () {
|
||
|
if (this.observer) {
|
||
8 years ago
|
this.callbacks = {};
|
||
8 years ago
|
this.observer.disconnect();
|
||
8 years ago
|
this.observer = null;
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
export default IntersectionObserverWrapper;
|