Google Analytics and Backbone.js

送分小仙女□ 提交于 2019-12-13 05:47:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!