Routes optional params

1,047 views
Skip to first unread message

Kake

unread,
Apr 29, 2013, 3:37:16 AM4/29/13
to sam...@googlegroups.com

I have an app where I use the Url as state holder for the app. And also provide deep linking functionality. This require the use of multiple optional params. I could do it using ugly query string but would like to be able to use “good-looking” urls..

I.e.

this.get('#/test/:p1/?:p2?/?:p3?/?:p4?/?:p5?/?:p6?/', function () {

       $("#params").empty().show().append("<p>" + this.params + "</p>");

});

url: http://localhost:6495/sammy.html#/test/v1/v2/v3/v4/v5/v6/

Gives: {"p1": v1,"p2": v2,"p3": v3,"p4": v4,"p5": v5,"p6": v6}

So http://localhost:6495/sammy.html#/test/v1/v6/ à {"p1": v1,"p2": v6,"p3": ,"p4": ,"p5": ,"p6": }

url: http://localhost:6495/sammy.html#/test/v1/////v6/

Gives: {"p1": v1,"p2": ,"p3": ,"p4": ,"p5": ,"p6": v6}

Which is not a practical solution..

 

Is there a way to use a key value approach with optional params?

I.e.:

A rout supporting

http://localhost:6495/sammy.html#/test/key1/value1/key2/value2/key3/value3/key4/value4/

and

http://localhost:6495/sammy.html#/test/key1/value1/key4/value4/

 

bonus question..

In many examples I see routes containing “!”  ('#!/key1/:key1/key2/:key2')

What is the meaning of the hashtag Exclamation Mark combo? It’s not working in my examples..

 

Andriy Zhdanov

unread,
Apr 30, 2013, 3:18:56 AM4/30/13
to sam...@googlegroups.com
Hi Kake,

Optional parameters are possible with regexp path, as documented: http://sammyjs.org/docs/routes

This works with multiple params in a single path. It does not work if you want to match strings that contain ‘/’. If you want that you can use Regexp and ‘splat’.Given a Regexp route:

get(/\#\/by_name\/(.*)/, function() {
        alert(this.params['splat']);
      });

And hash-bang (#!) is historical thing, for browsers that do not support push state for history. See http://hashbang.envoyat.com/pushstate-and-gotchas/ for example. although I'm not sure why it does not work for you.

Thank you.

Chris Ellenburg

unread,
Apr 30, 2013, 7:28:21 AM4/30/13
to sam...@googlegroups.com

this.get('#/test/:p1/:p2/:p3/:p4/:p5/:p6', runRoute);

this.get('#/test/:p1/:p2/:p3/:p4/:p5', runRoute);

this.get('#/test/:p1/:p2/:p3/:p4', runRoute);

this.get('#/test/:p1/:p2/:p3', runRoute);

...etc

function runRoute() {

//route code here

}

As for the route not working when you include the hash bang (#!/), it's because you must also include it in your URL. 


Hope this helps,

Chris


Sent from my iPhone
Reply all
Reply to author
Forward
0 new messages