问题
I am looking for a bit of help, I have been reading documentation on adding Analytics to backbone.js specifically this link and I think I fully understand it, but my issue is do I have to add the analytic tracking code to every page I want analytic's data from, if not can you point me in the right direction.
Any help is much appreciated. Thank You.
回答1:
According to the link in the question, you have to include the code only once probably in the router definition file.
The router.js (the file in which Backbone.Router
is defined) will look something like this :
router.js
//Include the google-analytics code here, first snippet from the code in
//this http://nomethoderror.com/blog/2013/11/19/track-backbone-dot-js-page-views-with-google-analytics/
var router=Backbone.Router.extend({
initialize: function() {
this.bind('route', this._pageView);
//your custom code goes here
},
_pageView: function() {
var path = Ba1ckbone.history.getFragment();
ga('send', 'pageview', {page: "/" + path});
},
//Other member definitions
});
回答2:
I recommend you to read this Google devs guide: https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
Here's my version of the solution (I've added the suggested call to ga('set'...)
before ga('send'...)
):
MyRouter = Backbone.Router.extend
...
initialize: () ->
# Track every route and call trackPage
@bind 'route', @trackPage
trackPage: () ->
url = Backbone.history.getFragment()
# Add a slash if neccesary
if not /^\//.test(url) then url = '/' + url
# Analytics.js code to track pageview
global.ga('set', page: url)
global.ga('send', 'pageview')
...
来源:https://stackoverflow.com/questions/24753579/google-analytics-and-backbone-js