Backbone JS Turbolinks未定义问题

时间:2014-06-23 23:03:07

标签: javascript jquery ruby-on-rails backbone.js turbolinks

我有一个主干JS和Turbolinks应用程序,我的代码如下:

$(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();
});

基本上,起初没有错误。但在第一页更改后,我收到错误:

Uncaught ReferenceError: AppRouter is not defined

1 个答案:

答案 0 :(得分:1)

你的范围问题,这应该有效:

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();
});

您已经在DOM-ready回调的范围内声明了AppRouter,然后尝试在'页面中引用它:load'没有定义的回调。在上面的代码中,它在全局范围内定义,因此两者都可以访问它。