Search code examples
javascriptbackbone.jsbackbone-routing

Backbone routing with arbitrary text


I have a page being redirected to from external to the backbone codebase. It has two parameters:

  • ID: An integer
  • CODE: A random printable ascii string (no # or & or ?, but can include - and always includes a /)

Not sure if CODE param is %encoded or not. Think I can get them to control that if required. But issue at the moment is just matching.

I am a maintenance programmer, not my app originally, so just trying to make code that "fits".

Most of the existing routes just take a single ID. e.g.

"account-edit-:accountId"    : "accountEditRoute"

But how do I pass my two params in to my process route. I have tried:

"process-:id-:code"    : "processCode"
"process-[^-]*-:code"  : "processCode"
"process-:id/:code"    : "processCode"
"process-:id/*"        : "processCode"

And my code handler is like:

processCode: function(id, code) {
...
}

I am always getting the unknown route handler. So how can I match the above.

Sorry if this is a dumb question - but they (wisely) don't normally let me near the front end, so all very new to me.


Solution

  • I believe you have to do it using the Router-route option with a regexp. The routes hash can only match simple patterns.

    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.

    initialize: function(options) {
    
     // Matches #page/10, passing "10"
      this.route("page/:number", "page", function(number){ ... });
    
     // Matches /117-a/b/c/open, passing "117-a/b/c" to this.open
     this.route(/^(.*?)\/open$/, "open");
    
    },
    
    open: function(id) { ... }