Skip to content
Swizec Teller - a geek with a

Mixing mixpanel into backbone

"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(
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);
} else {
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

Did you enjoy this article?

Published on January 24th, 2014 in Analytics, backbone, JavaScript, Mixpanel, Programming, Uncategorized

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their JS careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet:

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️