Backbone Routes - trigger route on page load

2019-05-22 22:34发布

This is a simple question, but I am new to routing and haven't been able to find an answer to this.

I have a Marionette Router (if I intimidate you, its really the same thing as a Backbone Router. Very simple).

sys.routes = {
  "app/:id": "onAppRoute",
};

sys.Router = new Marionette.AppRouter({
  controller: {
    onAppRoute: function(route) {
      console.log('Called app route!');
    },
  },
  appRoutes: sys.routes,
});

Backbone.history.start({pushState: true})  

This works - if you hit the back button my browser, the url will change within my Single Page Application and will call the onAppRoute function.

However, let's say I open a new browser window and paste in my page url to a certain 'app':

http://localhost/app/myApplication

This doesn't call the onAppRoute function. It doesn't even seem like it should, though, but I really don't know.

I want it to.

I don't know if I am doing it wrong, or if I should just manually fire it by grabbing my page url on page load, parsing it, then 'navigating' to that route. Seems hacky.

2条回答
小情绪 Triste *
2楼-- · 2019-05-22 23:16

Contrary to your intuition, backbone's default behaviour is to trigger matching routes on page load! cf. http://backbonejs.org/#Router - look for the option silent: true. You'd have to specify that for the router to IGNORE your matching routes on page load, i.e. not trigger the corresponding callbacks.

So your problem lies somewhere else: your routes do NOT match the url you have stated as an example. Clearly, you require an :id parameter, trailing http://localhost/app/myApplication. Therefore, http://localhost/app/myApplication/213 would cause your callback to be triggered on page load, given you didn't pass silent: true as an option to backbone.history.start().

If you want to match the 'root' url, i.e. no params, you would define the following route:

routes: {
    '/': someFunction
}
查看更多
我想做一个坏孩纸
3楼-- · 2019-05-22 23:38

The :id part is a parameter, which will be extracted by Backbone.Router and sent as an argument to onAppRoute. But in your URL you don't have any parameters /localhost/app/myApplication

查看更多
登录 后发表回答