Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. class ScrollManager {
  2. constructor() {
  3. this.subs = {};
  4. this._isTicking = false;
  5.  
  6. this._scrollAmt = this._getPageScrollAmt();
  7. }
  8.  
  9. _getPageScrollAmt() {
  10. return window.pageYOffset || document.documentElement.scrollTop;
  11. }
  12.  
  13. addListeners() {
  14. window.addEventListener('scroll', () => this._requestTick());
  15. }
  16.  
  17. removeListeners() {
  18. window.removeEventListener('scroll', () => this._requestTick());
  19. }
  20.  
  21. publish(scrollPosition) {
  22. for (const key in this.subs) {
  23. if (this.subs.hasOwnProperty(key)) {
  24. this.subs[key](scrollPosition);
  25. }
  26. }
  27. }
  28.  
  29. subscribe(key, fn) {
  30. this.subs[key] = fn;
  31. }
  32.  
  33. unsubscribe(key) {
  34. delete this.subs[key];
  35. }
  36.  
  37. _requestTick() {
  38. if (!this._isTicking) {
  39. requestAnimationFrame(() => this._onScroll());
  40. this._isTicking = true;
  41. }
  42. }
  43.  
  44. _onScroll() {
  45. this._scrollAmt = this._getPageScrollAmt();
  46. this.publish(this._scrollAmt);
  47.  
  48. this._isTicking = false;
  49. }
  50. }
  51.  
  52. export default ScrollManager;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement