observer.js 2.1 KB

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