observers-5706326b.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*!
  2. * All material copyright ESRI, All Rights Reserved, unless otherwise specified.
  3. * See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
  4. * v1.0.0-beta.97
  5. */
  6. 'use strict';
  7. /**
  8. * This utility ensures observers are created only for browser contexts.
  9. *
  10. * @param type - the type of observer to create
  11. * @param callback - the observer callback
  12. * @param options - the observer options
  13. */
  14. function createObserver(type, callback, options) {
  15. const Observer = getObserver(type);
  16. return new Observer(callback, options);
  17. }
  18. function getObserver(type) {
  19. // based on https://github.com/whatwg/dom/issues/126#issuecomment-1049814948
  20. class ExtendedMutationObserver extends window.MutationObserver {
  21. constructor(callback) {
  22. super(callback);
  23. this.observedEntry = [];
  24. this.callback = callback;
  25. }
  26. observe(target, options) {
  27. this.observedEntry.push({ target, options });
  28. return super.observe(target, options);
  29. }
  30. unobserve(target) {
  31. const newObservedEntries = this.observedEntry.filter((observed) => observed.target !== target);
  32. this.observedEntry = [];
  33. this.callback(super.takeRecords(), this);
  34. this.disconnect();
  35. newObservedEntries.forEach((observed) => this.observe(observed.target, observed.options));
  36. }
  37. }
  38. return (function () {
  39. return (type === "intersection"
  40. ? window.IntersectionObserver
  41. : type === "mutation"
  42. ? ExtendedMutationObserver
  43. : window.ResizeObserver);
  44. })();
  45. }
  46. exports.createObserver = createObserver;