Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js route optional parameter

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"
like image 298
TTT Avatar asked Mar 07 '12 11:03

TTT


2 Answers

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"
}
like image 78
Gabe H Avatar answered Nov 17 '22 06:11

Gabe H


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.

like image 16
Mauvis Ledford Avatar answered Nov 17 '22 06:11

Mauvis Ledford