2

Would like to set up a backbone route that matches a url that looks like this an all of its "intuitive" derivatives"

Base format: http://www.domain.com/PageName/:argument
Example:     http://www.domain.com/PageName/1234567890

The "intuitive" derivatives, in my opinion would be all of these urls:

Base url:                       http://www.domain.com/PageName/1234567890
With tailing slash:             http://www.domain.com/PageName/1234567890/
Base url with query params:     http://www.domain.com/PageName/1234567890?x=1
Tailing slash and query params: http://www.domain.com/PageName/1234567890/?x=1

The problem is that the backbone routes are getting super ugly:

routes:{    
    "PageName/:argument":           "main",
    "PageName/:argument/":          "main",
    "PageName/:argument/?:params":  "main",
    "PageName/:argument?:params":   "main"
}

I feel like this route should be able to be expressed in one line instead of 4 lines. Also, I don't need to be sending the url parameters through as an argument, I just wasn't able to get it to work without doing that.

How can I be specifying this route better?

Also, am I approaching this problem incorrectly? I feel like the fact that I had this problem to begin with may have to do with a more fundamental misunderstanding of the problem.

Thanks!

Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258

1 Answers1

3

Have you tried using .route() and regex? if you want to have optional route elements, regex is probably the way to go. It means defining your routes in .initialize() instead of the routes hash, but it would solve your problem and involve less code.

I haven't tested this, but I think it would look like:

initialize: function(options) {
    this.route(/PageName\/([^\/\?]+)\/?\??(.*)/, "main");
}

(Testing the regex exposes one small issue here: You'll get an empty string for the params argument, not undefined. But that's probably not an issue for you.)

nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
  • Yeah, this is probably what I should be doing. Thanks so much! – Chris Dutrow Sep 14 '12 at 15:40
  • how do you extract the query string in this example so you can pass it on? – Jonathan Mar 06 '15 at 12:27
  • From the docs: "Each matching capture from the route or regular expression will be passed as an argument to the callback." So the two parenthetical patterns should be passed to the `main` handler. – nrabinowitz Mar 09 '15 at 18:38