sammyjs optional parameters

偶尔善良 提交于 2019-11-30 14:19:53

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'}
this.get("#/:param1(/:param2)?", function (context) {
    var result = this.params['splat'];
});

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

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

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

this is an old post, still, if someone is looking for this:

another solution is to define two routes that map to the same function:

this.get('#route/:foo', module.foo_handler)
this.get('#route/:foo/:bar', module.foo_handler)

then in foo_handler check if the typeof(this.params.bar) is undefined, otherwise if it is defined the route with the bar param was used and bar has been specified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!