Backbone.js的路由器匹配可选参数 [英] Backbone.js Router Matching Optional Parameters
问题描述
我试图创造一个骨干路由器可以匹配可选参数。
I'm trying to create a backbone router that can match optional parameters.
考虑以下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 ....
}
如果我浏览到URL abc.com/#/职位/ P104 / 在页参数会 104 。但是,如果导航到abc.com/#/就业/工作/ 93 在作业ID 参数的未定义但是页参数 93
If I navigate to URL abc.com/#/jobs/p104/ the page parameter will be 104. However, if navigate to abc.com/#/jobs/job/93, the job_id parameter is undefined but the page parameter is 93.
所以,骨干路由器基本上匹配了秩序和叫不上名字的路线哈希参数。
So Backbone's router basically matches the routes hash parameters by order and not by name.
我知道解决办法是使用*图示和正则表达式拆分的参数,但我似乎无法得到正则表达式的部分工作(我的正则表达式是pretty生锈)。是否有人可以帮助?
I know the solution would be to use a *splat and split the parameters with regex, but I can't seem to get the regex part to work (my regex is pretty rusty). Can someone please help?
如果有比使用*图示,可以有人请共享一个更好的解决方案?
If there's a better solution than using *splat, can someone please share?
推荐答案
而不是用正则表达式搞乱它会更容易且不易出错正好有第二个功能。你可能会拥有在初始化函数来bindAll本作this.jobs工作。
Instead of messing with regexes it would be easier and less error prone just to have a second function. You will probably have to bindAll this in an initialize 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
}
这篇关于Backbone.js的路由器匹配可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!