Marionette.js appRouter not firing on app start

2019-02-27 13:10发布

I am currently integrating Marionette into an existing Backbone application.

I have an existing Backbone router in place, but am trying to implement a Marionette.AppRouter to take its place. The problem is that on a "Hard Refresh" on the url that the new Marionette router should pick up, it does not fire. If I navigate to another page, then go back to the url that did not fire on a hard refresh, it fires correctly. I cannot figure out why it works after I have navigated to another page and back again. Here is my code sample:

TestApp = new Backbone.Marionette.Application();
    var testAppController = {
        testLoadPage: function(){
            console.log('testLoadPage Fired'); //<---- DOES NOT FIRE ON HARD REFRESH
        }
    };
    TestAppRouter = Backbone.Marionette.AppRouter.extend({          
        appRoutes: {
            "!/:var/page": "testLoadPage",
            "!/:var/page/*path": "testLoadPage"
        },
        controller: testAppController,
        route: function(route, name, callback) {
            return Backbone.Router.prototype.route.call(this, route, name, function() {
                if (!callback) callback = this[name];
                this.preRoute();
                this.trigger.apply(this, ['beforeroute:' + name].concat(_.toArray(arguments)));
                callback.apply(this, arguments);
            });
        },
        preRoute: function() {
            app.showLoader(name, arguments);
        }
    });
    TestApp.addRegions({
        contentContainer: '#container'
    });
    TestApp.addInitializer(function(options){
        new TestAppRouter();
    });
    TestApp.start();

When I load the page: http://mysamplesite.com/#!/123/page directly, the Marionette router does not fire as it should.

However, if I load the page: http://mysamplesite.com/#!/123 and then navigate to http://mysamplesite.com/#!/123/page, the Marionette router fires correctly. Any ideas?

1条回答
做自己的国王
2楼-- · 2019-02-27 13:29

Did you call Backbone.history.start() after creating your router instance? If not, you need to do that. Routers won't run until this is called in your app, and you can't call this until at least one route has been instantiated. I usually do this:


TestApp.on("initialize:after", function(){
  if (Backbone.history){ Backbone.history.start(); }
});

hth

查看更多
登录 后发表回答