Search code examples
javascriptbackbone.jsscopebackbone-viewsbackbone-routing

Why do I need to specify window variable scope in backbone route filter?


I'm using the backbone route filter, https://github.com/fantactuka/backbone-route-filter, in my backbone.js app. It's a one page app, so I was trying to record pageviews using a KissMetrics event tracking snippet. Here is the code:

before: {
    '*any': function(fragment, args) {

    }
  },

  after: {
    '*any': function(fragment) {

      var _kmq = window._kmq || [];
      _kmq.push(['record', 'Viewed ' + fragment]);
    }
  },

The question is, the event wasn't tracking unless I specified the 'window' scope of the _kmq variable. Why? In my index.html, or the one page with all my js code, I have:

var _kmq = _kmq || [];

which I thought would make the variable at the global level automatically...this is the link to a typical implementation: http://support.kissmetrics.com/apis/javascript/index.html In every case I've seen prior the common api method worked, without setting the scope to window: http://support.kissmetrics.com/apis/javascript/javascript-specific/index.html

Why did I need to specify 'window._kmq' rather than just '_kmq'?


Solution

  • This looks like an issue of local versus global scoping (see What is the scope of variables in JavaScript? for some examples of this).

    Since you're including the Kiss Metrics Javascript on the page, it will be looking in the global (that is window._kmq) variable for event updates. To make sure you are pushing your event into that globally accessible variable, you need to specify that it lives in the global context (ie, window._kmq) versus a local context (ie, _kmq).

    In your Javascript code that lives directly on the page, the default scope is inside window, so var _kmq = ... is the same as window._kmq = ....

    In your Backbone router, this isn't the case: the scope inside there is isolated (that is, if you set var _kmq = ... inside the router, it isn't accessible anywhere except in that same block of code).