Last active
January 4, 2016 11:34
-
-
Save SimplGy/5349360 to your computer and use it in GitHub Desktop.
Abstraction for an SPA's Analytics Library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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