Backbone.js Router matching advanced parameters

I am trying to create a basic router that can match optional parameters.

Consider the following code:

routes: { '/jobs' : 'jobs', '/jobs/p:page' : 'jobs', '/jobs/job/:job_id' : 'jobs', '/jobs/p:page/job/:job_id' : 'jobs' } jobs: function(page, job_id){ // do stuff here .... } 

If I go to the abc.com/ # / jobs / p104 / URL , the page parameter will be 104 . However, if you go to abc.com/ # / jobs / job / 93 , the job_id parameter is undefined , but page 93 .

Thus, the underlying router basically matches the hash route parameters in order, not by name.

I know that the solution would be to use * splat and split the parameters with the regex, but I can't get the regex part to work (my regex is pretty rusty). Can anybody help?

If there is a better solution than using * splat, can anyone share it?

+7
source share
3 answers

Instead of messing with regular expressions, it would be easier and less error prone to just have a second function. You will probably have to bind this all together in the initialization function for this.jobs to work.

 routes: { '/jobs' : 'jobs', '/jobs/p:page' : 'jobs', '/jobs/job/:job_id' : 'jobsId', '/jobs/p:page/job/:job_id' : 'jobs' }, jobs: function(page, job_id){ // do stuff here .... }, jobsId: function(page, job_id){ this.jobs(undefined, job_id } 
+21
source

try this (one regex, works in all your input formats)

 var re = /\/jobs(?:\/p(\d+))?.*?(?:\/(\d+)|$)/; var matches = 'abc.com/#/jobs/p104/4'.match(re); var page=false;var job=false; if (matches != null) { var page = matches[1] || false; var job = matches[2] || false; }; alert("page:" + page + ",job:" + job) 

** matches the first pNNN segment, if any, and uses a non-greedy quantifier with a dot . that can eat anything .*? to traverse the line one at a time, so the second group (just / NNN) will also match if they are present. (?: exp ) are not exciting groups, they are grouped, but they do not "remember" anything.

+2
source

If you are going to do a lot, you can take a look at this template to wrap them carefully. For these purposes, however, the following regular expressions must be executed:

 /\/jobs\/p(\d+)/ => /jobs/pXXX /\/jobs\/p(\d+)\/job\/(\d+)/ => /jobs/pXXX/job/XXX 

You can then use String.match with the data you retrieve to retrieve the url fragments in question. Using strings instead of the splat variable:

 var matches = '/jobs/p18'.match(/\/jobs\/p(\d+)/); var page = matches[1]; var matches = '/jobs/p4/job/6/'.match(/\/jobs\/p(\d+)\/job\/(\d+)/); var page = matches[1]; var job = matches[2]; 
0
source

All Articles