sammyjs可选参数 [英] sammyjs optional parameters

查看:82
本文介绍了sammyjs可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道是否在sammy js路线中指定参数是可选的。

Just wondering if there is anyway to specify a parameter as optional in a sammy js route.

我见过你可以使用的地方

I've seen somewhere that you can use

route/:foo/?:bar

这会让sammy认为酒吧是可选的。但是,如果您在没有 bar 的情况下查询您的参数,则它将等于该网址的最后一个字符,例如

and that will trick sammy into thinking that bar is optional. However if you query your params without bar supplied you that it will equal the last character of the url for example

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

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

但是在这两种情况下都会填充栏没有办法检查它是否已供应。

but with bar getting populated in both cases there is no way to check if its been supplied.

有关此的任何提示吗?

推荐答案

当谈到可选参数和查询字符串时,Sammy实际上丢了球。我能让它工作得很好的唯一方法是使用正则表达式和splat对象。在你的例子中,你会写:

Sammy actually dropped the ball when it comes to optional parameters and querystrings. The only way I could get this to work fairly well is to use regular expressions and the splat object. In your example, you would write :

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

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

The downside is that you need the backslash at the end of the URL when the optional parameter is omitted.

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

The splat object is the actual result of the JavaScript match method and is an array.

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

这篇关于sammyjs可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆