Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. "use strict";
  2.  
  3. let listeners = [];
  4. let scrollTop = 0;
  5. let innerWidth = 0;
  6. let innerHeight = 0;
  7. let waitForRAF = false;
  8.  
  9. const supportsPassive = (function () {
  10. let supportsPassiveOption = false;
  11. try {
  12. const opts = Object.defineProperty({}, 'passive', {
  13. get: () => {
  14. supportsPassiveOption = true;
  15. }
  16. });
  17. window.addEventListener('test', null, opts);
  18. }
  19. catch (error) {}
  20. return supportsPassiveOption;
  21. })();
  22.  
  23.  
  24. export function addListener(func) {
  25. if (listeners.length === 0) {
  26. const opts = supportsPassive ? { passive: true } : false;
  27. window.addEventListener('scroll', handleUpdate, opts);
  28. window.addEventListener('resize', handleUpdate, false);
  29. listeners.push(func);
  30. } else if (!listeners.find(listener => listener === func)) {
  31. listeners.push(func);
  32. }
  33. }
  34.  
  35. export function removeListener(func) {
  36. listeners = listeners.filter(listener => listener !== func);
  37. if (listeners.length === 0) {
  38. const opts = supportsPassive ? { passive: true } : false;
  39. window.removeEventListener('scroll', handleUpdate, opts);
  40. window.removeEventListener('resize', handleUpdate, false);
  41. }
  42. }
  43.  
  44. export function triggerListener(func) {
  45. update();
  46. func(scrollTop, innerWidth, innerHeight);
  47. }
  48.  
  49. export function triggerAll() {
  50. update();
  51. dispatch();
  52. }
  53.  
  54.  
  55. function handleUpdate(event) {
  56. update();
  57. if (!waitForRAF) {
  58. window.requestAnimationFrame(() => {
  59. dispatch();
  60. waitForRAF = false;
  61. });
  62. waitForRAF = true;
  63. }
  64. }
  65.  
  66. function update() {
  67. const doc = document.documentElement;
  68. scrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
  69. innerWidth = window.innerWidth;
  70. innerHeight = window.innerHeight;
  71. }
  72.  
  73. function dispatch() {
  74. listeners.forEach(listener => {
  75. listener(scrollTop, innerWidth, innerHeight);
  76. });
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement