OLD | NEW |
(Empty) | |
| 1 // Incomplete / Naive implementation of ViewportObserver based on spec at: |
| 2 // https://docs.google.com/document/d/14y3ReQo_TU8N81V1okwmfT5LtRxj-20UiNJ3ddU9v
sI/edit?pli=1#heading=h.epew5hgbndxp |
| 3 window.ViewportObserver = function() { |
| 4 |
| 5 function ViewportObserver(callback) { |
| 6 this.callback_ = callback; |
| 7 this.targets_ = []; |
| 8 this.changedRecords_ = []; |
| 9 this.notifyNow_ = this.notify_.bind(this); |
| 10 } |
| 11 |
| 12 ViewportObserver.prototype.observe = function(target) { |
| 13 if (this.targets_.indexOf(target) != -1) |
| 14 return; |
| 15 var listenOn = target == document.scrollingElement ? document : target; |
| 16 listenOn.addEventListener('scroll', this.onScroll_.bind(this, target)); |
| 17 this.targets_.push(target); |
| 18 this.onScroll_(target); |
| 19 }; |
| 20 |
| 21 ViewportObserver.prototype.onScroll_ = function(target) { |
| 22 this.changedRecords_.push({ |
| 23 time: performance.now(), |
| 24 viewport: getViewportRect(target), |
| 25 element: target |
| 26 }); |
| 27 this.notify_(); |
| 28 }; |
| 29 |
| 30 ViewportObserver.prototype.scheduleNotify_ = function() { |
| 31 if (!this.timeoutId_) |
| 32 this.timeoutId_ = setTimeout(this.notifyNow_, 0); |
| 33 }; |
| 34 |
| 35 ViewportObserver.prototype.notify_ = function() { |
| 36 clearTimeout(this.timeoutId_); |
| 37 this.timeoutId_ = undefined; |
| 38 this.callback_(this.changedRecords_); |
| 39 this.changedRecords_.length = 0; |
| 40 }; |
| 41 |
| 42 return ViewportObserver; |
| 43 }(); |
OLD | NEW |