Search code examples
javascriptjqueryruby-on-railsbackbone.jsturbolinks

Backbone JS Turbolinks Not defined issue


I have a backbone JS and Turbolinks app where my code looks like:

$(function() {

   var AppRouter = Backbone.Router.extend({
     routes: {
       '': 'music',
       'song/:musicID': 'songList'
     },
     ...FUNCTIONS GO HERE
   });

   var appRouter = new AppRouter();
   Backbone.history.start({ pushState: true, hashChange: false });

});

$(document).on('page:load', function (){
   Backbone.history.stop();
   var appRouter = new AppRouter();
});

Basically, at first there are no errors. But after the first page change, I get the error:

Uncaught ReferenceError: AppRouter is not defined

Solution

  • You've got a problem with scope, this should work:

    var AppRouter = Backbone.Router.extend({
      routes: {
        '': 'music',
        'song/:musicID': 'songList'
      },
      ...FUNCTIONS GO HERE
    });
    
    $(function() {
    
       var appRouter = new AppRouter();
       Backbone.history.start({ pushState: true, hashChange: false });
    
    });
    
    $(document).on('page:load', function (){
       Backbone.history.stop();
       var appRouter = new AppRouter();
    });
    

    You had declared AppRouter within the scope of the DOM-ready callback and were then trying to reference it within the 'page:load' callback where it wasn't defined. In the code above it's defined in the global scope thus both have access to it.