0

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'?

YPCrumble
  • 26,610
  • 23
  • 107
  • 172

1 Answers1

1

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).

Community
  • 1
  • 1
JJ Geewax
  • 10,342
  • 1
  • 37
  • 49
  • What is the scope of the backbone router? – YPCrumble Sep 20 '13 at 02:15
  • Gotcha, thank you! I was confused because when I include `_kmq` in a _view_, the event passes fine. So the scope of the view is at window and that of the router is not? – YPCrumble Sep 20 '13 at 02:18
  • I'd need to see more code, but I'd guess that you're *referencing* `_kmq` which is defaulting to the global scope. When you *set* `var _kmq` inside the method (like you were doing) it is set in the local scope only. – JJ Geewax Sep 20 '13 at 02:23