Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    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(
      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);
            } 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.

    Nifty.

    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
    Published on January 24th, 2014 in Analytics, backbone, JavaScript, Mixpanel, Programming, Uncategorized

    Did you enjoy this article?

    Continue reading about Mixing mixpanel into backbone

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

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

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

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

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

    Created by Swizec with ❤️