Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Abstraction for an SPA's Analytics Library
define(
[]
() ->
_analyticsSites =
DEMO: 1
LOCALHOST: 2
_libUrl = (server) ->
'js!' + server + '/js/piwik.js'
_trackerUrl = (server) ->
server + '/piwik.php'
_errLibrary = -> console.log 'Error getting the analytics library'
class Analytics
constructor: (options) ->
throw new Error('options.cfg is required') unless options and options.cfg
@server = options.cfg.analyticsServer
# If there's a url, analytics is enabled
if !@server
console.log 'Analytics is not configured. To enable analytics set the config property "analyticsServer" to a valid URL'
return undefined
@_queue = []
@_getLibrary()
_getLibrary: ->
curl(
_libUrl @server
@_gotLibrary.bind @
_errLibrary
)
_gotLibrary: ->
@tracker = Piwik.getTracker _trackerUrl(@server)
@tracker.setSiteId _analyticsSites.LOCALHOST
@track command for command in @_queue
@_queue = []
setClientName: (client) ->
return unless @tracker
@tracker.setCustomVariable 1, 'clientName', client, "visit"
@
setUserName: (user) ->
return unless @tracker
@tracker.setCustomVariable 2, 'userName', user, "visit"
@
# Meant for user interaction events
track: (pageName) ->
if @tracker
console.log 'Analytics Tracking: ' + pageName
@tracker.trackPageView(pageName)
else
console.log 'Analytics Queued: ' + pageName
@_queue = @_queue || []
@_queue.push(pageName) # If the tracker isn't available yet, we'll save the event to track later
@
# Intended for code error events that we want to know about at iSirona HQ
trackErr: (errName) ->
@track "error/#{errName}"
Analytics
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.