why route of backbone needs the default route

2019-07-22 08:21发布

问题:

I create a test case with backbone.js @: http://jsfiddle.net/VWBvs/5/

Route is defined as

var AppRouter = Backbone.Router.extend({
        routes: {
            "/posts/:id" : "getPost",
            "/download/*path": "downloadFile",  
            "*actions" : "defaultRoute"
        },
        getPost: function(id) {
            alert(id);
        },
        defaultRoute : function(actions){
            alert(actions);
        },
        downloadFile: function( path ){ 
            alert(path); // user/images/hey.gif 
        },
        loadView: function( route, action ){ 
            alert(route + "_" + action); // dashboard_graph 
        }
    });

    var app_router = new AppRouter;

    Backbone.history.start();​

When I change the function

  defaultRoute : function(actions){
            alert(actions);
        },

to

defaultRoute : function(actions){
            var action = actions
        },

all other routes won't work which means no dialog pops up.

But when rechange the code ,all is ok.

It's really weird and make me confused. SOS sincerely ......

回答1:

As you have the code defaultRoute is the only route that ever fires. If you want the other two routes to fire you have to remove the leading slashes.

routes: {
  "posts/:id" : "getPost",
  "download/*path": "downloadFile",  
  "*actions" : "defaultRoute"
}