eventTracking.coffee 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # For sending event data to metabase and google analytics
  2. # ---
  3. # by default,
  4. # event not sent to MB.
  5. # for MB, add event-tracking-mb='true'
  6. # by default, event sent to MB via sendMB
  7. # event not sent to GA.
  8. # for GA, add event-tracking-ga attribute, where the value is the GA category
  9. # Either GA or MB can use the attribute event-tracking-send-once='true' to
  10. # send event just once
  11. # MB will use the key and GA will use the action to determine if the event
  12. # has been sent
  13. # event-tracking-trigger attribute is required to send event
  14. isInViewport = (element) ->
  15. elTop = element.offset().top
  16. elBtm = elTop + element.outerHeight()
  17. viewportTop = $(window).scrollTop()
  18. viewportBtm = viewportTop + $(window).height()
  19. elBtm > viewportTop && elTop < viewportBtm
  20. define [
  21. 'base'
  22. ], (App) ->
  23. App.directive 'eventTracking', ['event_tracking', (event_tracking) ->
  24. return {
  25. scope: {
  26. eventTracking: '@',
  27. eventSegmentation: '=?'
  28. }
  29. link: (scope, element, attrs) ->
  30. sendGA = attrs.eventTrackingGa || false
  31. sendMB = attrs.eventTrackingMb || false
  32. sendMBFunction = if attrs.eventTrackingSendOnce then 'sendMBOnce' else 'sendMB'
  33. sendGAFunction = if attrs.eventTrackingSendOnce then 'sendGAOnce' else 'send'
  34. segmentation = scope.eventSegmentation || {}
  35. segmentation.page = window.location.pathname
  36. sendEvent = (scrollEvent) ->
  37. ###
  38. @param {boolean} scrollEvent Use to unbind scroll event
  39. ###
  40. if sendMB
  41. event_tracking[sendMBFunction] scope.eventTracking, segmentation
  42. if sendGA
  43. event_tracking[sendGAFunction] attrs.eventTrackingGa, attrs.eventTrackingAction || scope.eventTracking, attrs.eventTrackingLabel || ''
  44. if scrollEvent
  45. $(window).unbind('resize scroll')
  46. if attrs.eventTrackingTrigger == 'load'
  47. sendEvent()
  48. else if attrs.eventTrackingTrigger == 'click'
  49. element.on 'click', (e) ->
  50. sendEvent()
  51. else if attrs.eventTrackingTrigger == 'hover'
  52. timer = null
  53. timeoutAmt = 500
  54. if attrs.eventHoverAmt
  55. timeoutAmt = parseInt(attrs.eventHoverAmt, 10)
  56. element.on 'mouseenter', () ->
  57. timer = setTimeout((-> sendEvent()), timeoutAmt)
  58. return
  59. .on 'mouseleave', () ->
  60. clearTimeout(timer)
  61. else if attrs.eventTrackingTrigger == 'scroll'
  62. if !event_tracking.eventInCache(scope.eventTracking)
  63. $(window).on 'resize scroll', () ->
  64. _.throttle(
  65. if isInViewport(element) && !event_tracking.eventInCache(scope.eventTracking)
  66. sendEvent(true)
  67. , 500)
  68. }
  69. ]