“Hey, so nobody’s looked at our Mixpanel integration in months and the product has changed a lot, so uh … can you fix that?”

Every developer’s favourite thing to hear. Logs and metrics going out of sync with the product they’re logging and metricsing. Always fun to fix …

How can we avoid ever fixing this again?

We’d like an automagic logging or metrics system that fulfills two criteria:

  • self-adapting
  • doesn’t show up in the code

In my case, I had to fix an old javascript integration of Mixpanel. Our approach was a mix of globally assigning event listeners and peppering our view/model/whatever code with mixpanel.track calls.

The problem is that global event listeners will eventually fall out of sync when a class name changes or a link is removed. Peppering your code with calls to tracking code is even more brittle.

Tracking calls are essentially comments on your code. Comments and code always drift apart. Always. It’s just a fact. The same thing happens to tracking calls.

Except it’s even worse than comments. At least comments are helpful in theory. Tracking code just muddies the logic of your functions. do_something becomes do_something_and_track_business_event_X.

Of course you won’t name your functions like that because you’re not a tool, but you have introduced an extra side-effect. Nobody likes strange side-effects. Especially the kind that make calls to remote services.

Therefore, the only solution is moving tracking code an abstraction layer higher. Instead of relying on everyone in the team to maintain tracking calls, move them into the framework they’re using.

For us it’s Backbone. So last night I wrote a simple 30 line mixin for Backbone views that makes sure we track everything.

// copied straight from backbone
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// inspired by Backbone
Backbone.View.prototype.delegateEvents = _.wrap(
    Backbone.View.prototype.delegateEvents, function (fn, events) {
        if (!(events || (events = _.result(this, 'events')))) return this;
        var track = _.bind(function (event) {
            var $target = $(event.currentTarget),
                event_name = $target.attr("data-mixpanel"),
                data = !!this.model ? this.model.toJSON() : {};
            if (event_name) {
                mixpanel.track(event_name, data);
        }, this);
        for (var key in events) {
            var match = key.match(delegateEventSplitter),
                type = match[1],
                selector = match[2];
            if (type == "click" || type == "submit") {
                if (selector === "") {
                    this.$el.on(type, track);
                    this.$el.on(type, selector, track);
        return fn.apply(this);

The code wraps and is heavily inspired by Backbone.View.delegateEvents, which is called when a new view is instantiated. Its job is to go through the events configuration hash and bind the view’s event listeners to correct events on particular HTML elements.


My mixin does the same, but only cares about click and submit events since those represent most user actions. Every such event is bound to a simple track function, which takes the data-mixpanel property from the element as an event’s business name, and uses the view’s whole model as meta data.

I figured the more data we can collect the better. You never know what you’re going to need in the future.

From now on, we just have to add a data-mixpanel property to any element whose user actions we want to track. No property, no tracking. Simple.

And yes, I know what you’re thinking, surely there’s already a plugin for this. There is, it’s called backbone-mixpanel. Looks like a pretty good solution, but for once I wanted to put my NotInventedHere blinds on and make something myself. ๐Ÿ™‚

Either way, this should remove the friction between us and good actionable metrics.

PS: yes, before you get up in arms, I do need to add the code that cleans up events by wrapping the Backbone.View.undelegateEvents method.

Enhanced by Zemanta

Learned something new? ๐Ÿ’Œ

Join 8,400+ people becoming better Frontend Engineers!

Here's the deal: leave your email and I'll send you an Interactive ES6 Cheatsheet ๐Ÿ“– right away.ย  After that you'll get an email once a week with my writings aboutย React, JavaScript,ย  andย life as an engineer.

You should follow me on twitter, here.