Search code examples
javascriptbackbone.jsurl-routingbackbone-routing

Backbone routes with optional '/'s and query parameters


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!


Solution

  • 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.)