Search code examples
javascriptjquerymixpanel

How to abstract a JavaScript Function (mixpanel)


I'm working to abstract a mixpanel tracking function. The function workings like this:

mixpanel.track("Hello World");
mixpanel.track("Hello World", { "ab_version": 2});
mixpanel.track("Hello World", { "ab_version": 2, "color" : "red"});

I'm trying to abstract this so event tracking is not tied to Mixpanel in my application. I've tried doing:

MyApp.eventTrack("Hello World", { "ab_version": 2});

(function() {
    MyApp.eventTrack = function(data) {
        mixpanel.track(data);
    }
}());

However this is not working properly. Any suggestions how I can make MyApp.eventTrack pass the parameters properly to work with mixpanel.track?


Solution

  • Your code is missing the second argument:

    (function() {
        MyApp.eventTrack = function(firstArg, secondArg) {
            mixpanel.track(firstArg, secondArg);
        }
    }());
    

    Alternatively, you can handle an unbounded number of arguments by using apply and arguments together:

    MyApp.eventTrack = function() {
        mixpanel.track.apply(mixpanel, arguments);
    }
    

    This calls mixpanel.track with all arguments passed to MyApp.eventTrack.