Backbone.js route optional parameter

2019-03-09 07:19发布

问题:

Is it possible to have optional parameters in a Backbone.js route?

e.g this:

routes:
  "search/[:query]": "searchIndex"

instead of:

routes:
  "search/": "searchIndex"
  "search/:query": "searchIndex"

回答1:

As of Backbone 0.9.9, you can add optional paramaters with parentheses.

For example in your routes object you can define an optional route part like this:

routes: {
    "organize(/:action)": "displayOrganize"
}

Now the url path will match /#organize and routes like /#organize/create.

Keep in mind that if you need routes like /#organize/ (with a trailing slash) to be recognized, you can do:

routes: {
    "organize(/)(:action)": "displayOrganize"
}


回答2:

Probably the most easiest way is just declare more than one route, one with the extra arg,one without:

routes:{
        "authProxy/:hash": "authProxy",                                                                                                                                                                 
        "authProxy/:hash/:url": "authProxy"
}

then just check for them in your method:

authProxy: function(hash, url){
    if (url){
      // Hash and URL.
    }else{
      // Just hash.
    }
}

Note that I like this much better than the other two answers because it's very easy for another developer to understand what's going on.



回答3:

You can add regex based routes manually using the route method:

route router.route(route, name, [callback])

Manually create a route for the router, The route argument may be a routing string or regular expression. Each matching capture from the route or regular expression will be passed as an argument to the callback.

So something like this should work:

this.route(/^search\/(.*)?/, 'searchIndex');

Then searchIndex would get called with your nothing or your :query as its argument.

The downside is that you can't put regex routes into your routes object. You could add all your routes with route inside your router's initialize method if you wanted to keep them all together.



回答4:

What about using the *splat:

routes router.routes

The routes hash maps URLs with parameters to functions on your router, similar to the View's events hash. Routes can contain parameter parts, :param, which match a single URL component between slashes; and splat parts *splat, which can match any number of URL components.

For example, a route of "search/:query/p:page" will match a fragment of #search/obama/p2, passing "obama" and "2" to the action. A route of "file/*path" will match #file/nested/folder/file.txt, passing "nested/folder/file.txt" to the action.