Backbone.js route optional parameter

前端 未结 4 385
生来不讨喜
生来不讨喜 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:36

    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"
    }
    
    0 讨论(0)
  • 2021-02-01 02:39

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 02:45

    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.

    0 讨论(0)
提交回复
热议问题