Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sammyjs optional parameters

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

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'}

and

'/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.

Any tips on this?

like image 551
mat-mcloughlin Avatar asked Apr 08 '13 09:04

mat-mcloughlin


1 Answers

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'];
});

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

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'}
like image 151
rivarolle Avatar answered Nov 08 '22 19:11

rivarolle