Additional options sammyjs

It’s just interesting if in any case you specify the parameter as optional in the sammy js route.

I saw somewhere that you can use

route/:foo/?:bar 

and it will work if you think that the bar is optional. However, if you request your parameters without bar , provided you that it will be equal to the last character of the URL, for example

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

and

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

but with the filling of the bar in both cases it is impossible to verify whether it was provided.

Any tips on this?

+6
source share
3 answers

Sammy actually threw the ball when it came to optional parameters and requests. The only way I could work well is to use regular expressions and a splat object. In your example, you should write:

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

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

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

 '#/route/test/' => {result[0]: 'test', result[1]: ''} '#/route/test/chicken' => {result[0]: 'test', result[1]: 'chicken'} 
+12
source
 this.get("#/:param1(/:param2)?", function (context) { var result = this.params['splat']; }); 

The only problem with this approach is that param2 will start with '/', but this can be easily removed.

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

 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();}); }); 
0
source

All Articles