observers-9f44e9b3.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. /**
  7. * This utility ensures observers are created only for browser contexts.
  8. *
  9. * @param type - the type of observer to create
  10. * @param callback - the observer callback
  11. * @param options - the observer options
  12. */
  13. function createObserver(type, callback, options) {
  14. const Observer = getObserver(type);
  15. return new Observer(callback, options);
  16. }
  17. function getObserver(type) {
  18. // based on https://github.com/whatwg/dom/issues/126#issuecomment-1049814948
  19. class ExtendedMutationObserver extends window.MutationObserver {
  20. constructor(callback) {
  21. super(callback);
  22. this.observedEntry = [];
  23. this.callback = callback;
  24. }
  25. observe(target, options) {
  26. this.observedEntry.push({ target, options });
  27. return super.observe(target, options);
  28. }
  29. unobserve(target) {
  30. const newObservedEntries = this.observedEntry.filter((observed) => observed.target !== target);
  31. this.observedEntry = [];
  32. this.callback(super.takeRecords(), this);
  33. this.disconnect();
  34. newObservedEntries.forEach((observed) => this.observe(observed.target, observed.options));
  35. }
  36. }
  37. return (function () {
  38. return (type === "intersection"
  39. ? window.IntersectionObserver
  40. : type === "mutation"
  41. ? ExtendedMutationObserver
  42. : window.ResizeObserver);
  43. })();
  44. }
  45. export { createObserver as c };