2013-04-08 63 views
6

只是想知道是否有任何指定参数作为sammy js路由中的可选参数。sammyjs可选参数

我见过的地方,你可以使用

route/:foo/?:bar 

,这将诱使萨米以为酒吧是可选的。但是,如果您查询您的PARAMS没有bar提供您它将等于URL的最后一个字符例如

'#/route/test' => {foo: 'test', bar: 't'} 

'/route/test/chicken' => {foo: 'test', bar: 'chicken' } 

但酒吧在两种情况下得到填充有没有办法检查它是否提供。

对此有任何提示?

回答

12

当谈到可选参数和querystrings时,Sammy实际上放弃了球。我可以很好地工作的唯一方法是使用正则表达式和splat对象。在你的榜样,你可以这样写:

this.get(/\#\/route\/(.*)\/(.*)/, function (context) { 
     var result = this.params['splat']; 
}); 

的缺点是,你需要在URL的末尾反斜杠省略了可选的参数时。

splat对象是JavaScript匹配方法的实际结果,并且是数组

'#/route/test/' => {result[0]: 'test', result[1]: ''} 
'#/route/test/chicken' => {result[0]: 'test', result[1]: 'chicken'} 
+0

没错球被丢弃。这就是我正在看的,它不会与我一起切割,目前正在编写一个补丁,以便它可以处理它们:D – 2013-04-11 09:53:46

+0

+1用于解释splat对象。谢谢! :) – 2013-09-03 23:18:40

2
this.get("#/:param1(/:param2)?", function (context) { 
    var result = this.params['splat']; 
}); 

这种方法唯一的问题是参数2将与“/”开始,但是这可以很容易地取出。

'#/go' => {result[0]: 'go', result[1]: ''} 
'#/go/here' => {result[0]: 'go', result[1]: '/here'} 
0

this.get('#/product/(:id)?', function(context) { 
 
     var id = this.params['id']; 
 
     context.app.swap(''); 
 
     context.render('templates/product.template', {base_url:base_url}) 
 
      .appendTo(context.$element()).then(function() {loadProduct();}); 
 
    });