event.coffee 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. define [
  2. "base"
  3. "modules/localStorage"
  4. ], (App) ->
  5. CACHE_KEY = "mbEvents"
  6. send = (category, action, attributes = {})->
  7. ga('send', 'event', category, action)
  8. event_name = "#{action}-#{category}"
  9. Intercom?("trackEvent", event_name, attributes)
  10. App.factory "event_tracking", ($http, localStorage) ->
  11. _getEventCache = () ->
  12. eventCache = localStorage CACHE_KEY
  13. # Initialize as an empy object if the event cache is still empty.
  14. if !eventCache?
  15. eventCache = {}
  16. localStorage CACHE_KEY, eventCache
  17. return eventCache
  18. _eventInCache = (key) ->
  19. curCache = _getEventCache()
  20. curCache[key] || false
  21. _addEventToCache = (key) ->
  22. curCache = _getEventCache()
  23. curCache[key] = true
  24. localStorage CACHE_KEY, curCache
  25. return {
  26. send: (category, action, label, value)->
  27. ga('send', 'event', category, action, label, value)
  28. sendMB: (key, segmentation = {}) ->
  29. $http {
  30. url: "/event/#{key}",
  31. method: "POST",
  32. data: segmentation
  33. headers: {
  34. "X-CSRF-Token": window.csrfToken
  35. }
  36. }
  37. sendMBSampled: (key, segmentation) ->
  38. @sendMB key, segmentation if Math.random() < .01
  39. sendMBOnce: (key, segmentation) ->
  40. if ! _eventInCache(key)
  41. _addEventToCache(key)
  42. @sendMB key, segmentation
  43. }
  44. #header
  45. $('.navbar a').on "click", (e)->
  46. href = $(e.target).attr("href")
  47. if href?
  48. ga('send', 'event', 'navigation', 'top menu bar', href)