all files / src/ video-tracker.js

100% Statements 22/22
80% Branches 4/5
100% Functions 6/6
100% Lines 22/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 7113×                                     20× 13× 13× 10× 10×                               11×       10× 10×                          
const vpaidLifeCycle = require('./vpaid-life-cycle')
const quartiles = [
  {
    value: 0,
    name: vpaidLifeCycle[0]
  },
  {
    value: 0.25,
    name: vpaidLifeCycle[1]
  },
  {
    value: 0.50,
    name: vpaidLifeCycle[2]
  },
  {
    value: 0.75,
    name: vpaidLifeCycle[3]
  }
]
function handleTimeupdate () {
  const upcomingQuartileIndex = this.quartileIndexEmitted + 1
  const upcomingQuartile = quartiles[upcomingQuartileIndex]
  if (upcomingQuartile && this.el.currentTime / this.el.duration > upcomingQuartile.value) {
    this.emit(upcomingQuartile.name)
    this.quartileIndexEmitted = upcomingQuartileIndex
  }
}
 
function handleEnded () {
  this.emit(vpaidLifeCycle[4])
  // Garbage collect event listeners
  this.removeEventListeners()
}
 
class VideoTracker {
  /**
   * [constructor description]
   * @param  {[type]} el      [description]
   * @param  {TinyEmitter} emitter [description]
   * @return {[type]}         [description]
   */
  constructor (el, emitter, prefix = 'AdVideo') {
    this.el = el
    this.emitter = emitter
    this.prefix = prefix
    this.quartileIndexEmitted = -1
    this.addEventListeners()
  }
 
  emit (...rest) {
    const eventName = this.prefix + rest[0]
    return this.emitter.emit.apply(this.emitter, [eventName].concat(rest.splice(1)))
  }
 
  addEventListeners () {
    this.events = {
      handleTimeupdate: handleTimeupdate.bind(this),
      handleEnded: handleEnded.bind(this)
    }
    this.el.addEventListener('timeupdate', this.events.handleTimeupdate)
    this.el.addEventListener('ended', this.events.handleEnded)
  }
 
  removeEventListeners () {
    this.el.removeEventListener('timeupdate', this.events.handleTimeupdate)
    this.el.removeEventListener('ended', this.events.handleEnded)
  }
}
 
module.exports = VideoTracker