about summary refs log tree commit diff
path: root/app/javascript/flavours/glitch/util/intersection_observer_wrapper.js
blob: 2b24c65831d87c27d71ed184dd7899d5772fb89e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 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);
    }
  }

  unobserve (id, node) {
    if (this.observer) {
      delete this.callbacks[id];
      this.observer.unobserve(node);
    }
  }

  disconnect () {
    if (this.observer) {
      this.callbacks = {};
      this.observer.disconnect();
      this.observer = null;
    }
  }

}

export default IntersectionObserverWrapper;