-
Notifications
You must be signed in to change notification settings - Fork 0
/
meq.js
82 lines (69 loc) · 3.34 KB
/
meq.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*!
############################
### Mixpanel Event Queue ###
############################
VERSION: 0.1.2
LICENSE: Apache 2.0
DESCRIPTION: Event queuing wrapper for the official Mixpanel JavaScript library. For docs & examples, see README or http://github.com/skotzko/mixpanel-event-queue
WRITTEN BY: Andrew Skotzko (http://github.com/skotzko)
*/
// **NOTE**: This wrapper assumes you will be loading the standard Mixpanel JS library into the window.mixpanel namespace.
var _meq = (function(){
var wrapper = {
QUEUE_NAME: '_ch_mp_queue',
mixpanel: function(/* string */ functionName, /* string */ eventName, /* object */ properties) {
var mixPanelArgs = Array.prototype.slice.call(arguments);
var functionName = mixPanelArgs.shift();
if (!functionName) {
console.error('Must provide a function name to call.');
return;
}
if (!mixPanelArgs || (Object.prototype.toString.call(mixPanelArgs) === '[object Array]') !== true || mixPanelArgs.length <= 0) {
console.error('Must provide arguments to pass on to Mixpanel, in order/format desired by their API calls.');
return;
}
if (typeof(window[_meq.QUEUE_NAME]) == 'undefined') {
window[_meq.QUEUE_NAME] = [];
}
var queue = window[_meq.QUEUE_NAME];
var mixpanel = window.mixpanel;
// once mixpanel is loaded and has tracking functions available, we hand off to it
if (mixpanel && mixpanel.__loaded && functionName) {
// convert event name string into namespacing array
var funcNamespace = functionName.split('.');
// loop through funcNamespace to get final tracking function
// e.g. ['people', 'set'] === mixpanel.people.set
var trackingFunc = mixpanel;
var trackingFuncContext = mixpanel;
var length = funcNamespace.length;
for (var i=0; i<length; i++) {
if (i == length - 1) {
// context in which the function is executed is the direct parent object
// of the final call (i.e. on a call to mixpanel.people.set, "this" == mixpanel.people)
trackingFuncContext = trackingFunc;
}
trackingFunc = trackingFunc[funcNamespace[i]];
}
// hand off to Mixpanel
trackingFunc.apply(trackingFuncContext, mixPanelArgs);
} else if (queue) {
// if mixpanel does not exist, queue up events
queue.push(arguments);
}
},
flush: function() {
// once mixpanel is loaded, it calls back to here to flush any queued events
// iterate over queue and flush events to their system
var queue = window[_meq.QUEUE_NAME];
// loop over and clean out event queue
// use .apply so we can invoke w/ args as an array, which is how they're stored
if (queue && queue.length > 0) {
for (var i in queue){
_meq.mixpanel.apply(window.mixpanel, queue[i]);
}
}
window[_meq.QUEUE_NAME] = [];
}
}
return wrapper;
})();