observer.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { getWindow } from 'ssr-window';
  2. export default function Observer({
  3. swiper,
  4. extendParams,
  5. on,
  6. emit
  7. }) {
  8. const observers = [];
  9. const window = getWindow();
  10. const attach = (target, options = {}) => {
  11. const ObserverFunc = window.MutationObserver || window.WebkitMutationObserver;
  12. const observer = new ObserverFunc(mutations => {
  13. // The observerUpdate event should only be triggered
  14. // once despite the number of mutations. Additional
  15. // triggers are redundant and are very costly
  16. if (mutations.length === 1) {
  17. emit('observerUpdate', mutations[0]);
  18. return;
  19. }
  20. const observerUpdate = function observerUpdate() {
  21. emit('observerUpdate', mutations[0]);
  22. };
  23. if (window.requestAnimationFrame) {
  24. window.requestAnimationFrame(observerUpdate);
  25. } else {
  26. window.setTimeout(observerUpdate, 0);
  27. }
  28. });
  29. observer.observe(target, {
  30. attributes: typeof options.attributes === 'undefined' ? true : options.attributes,
  31. childList: typeof options.childList === 'undefined' ? true : options.childList,
  32. characterData: typeof options.characterData === 'undefined' ? true : options.characterData
  33. });
  34. observers.push(observer);
  35. };
  36. const init = () => {
  37. if (!swiper.params.observer) return;
  38. if (swiper.params.observeParents) {
  39. const containerParents = swiper.$el.parents();
  40. for (let i = 0; i < containerParents.length; i += 1) {
  41. attach(containerParents[i]);
  42. }
  43. } // Observe container
  44. attach(swiper.$el[0], {
  45. childList: swiper.params.observeSlideChildren
  46. }); // Observe wrapper
  47. attach(swiper.$wrapperEl[0], {
  48. attributes: false
  49. });
  50. };
  51. const destroy = () => {
  52. observers.forEach(observer => {
  53. observer.disconnect();
  54. });
  55. observers.splice(0, observers.length);
  56. };
  57. extendParams({
  58. observer: false,
  59. observeParents: false,
  60. observeSlideChildren: false
  61. });
  62. on('init', init);
  63. on('destroy', destroy);
  64. }