Backbone.js route optional parameter

前端 未结 4 454
生来不讨喜
生来不讨喜 2021-02-01 01:51

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

e.g this:

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

instead of:

4条回答
  •  没有蜡笔的小新
    2021-02-01 02:42

    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.

提交回复
热议问题