Skip to content

Instantly share code, notes, and snippets.

@matthewwithanm
Created December 3, 2013 16:27
Show Gist options
  • Save matthewwithanm/7772304 to your computer and use it in GitHub Desktop.
Save matthewwithanm/7772304 to your computer and use it in GitHub Desktop.
Google Analytics Event Tracking w/Callbacks & Timeout
# A simple "once" implementation. Can be replaced with _.once or similar.
once = (func) ->
ran = false
->
return if ran
ran = true
func.apply this, arguments
func = null
undefined
# A simple "extend" implementation. Can be replaced with $.extend or similar.
extend = (target, sources...) ->
for source in sources
for own k, v of source
target[k] = v
target
# Logs an event, then executes a callback. If the tracking call hasn't completed
# after `timeout` ms, the errback is called.
#
# The following example calls submit form whether tracking was successful or
# not:
#
# gaTrackEvent(['send', 'event', 'category', 'action'], {page: '/my-new-page'}, submitForm, submitForm);
gaTrackEvent = (gaArgs, gaOpts, callback, errback, timeout = 1000) ->
done = once (error, args) ->
if error
errback args...
else
callback args...
newOpts = extend {}, gaOpts or {}
newOpts.hitCallback = (args...) ->
gaOpts?.hitCallback? args...
done false, args
ga gaArgs..., newOpts
setTimeout (-> done true), timeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment