user3792795
user3792795

Reputation: 41

How to get actual value of URL in Crossroads

Lets say, I have defined a route like :

route:{
  pattern: '/root/finder/*',
  handler: finderHandler
}

If the user makes a request with url /root/finder/1234, then this matches the above pattern, and the request will be handled by finderHandler() Now, in my finderHandler, I want to get the original url value. In this case, it's /admin/finder/1234, how can i get it?

Upvotes: 2

Views: 759

Answers (1)

Simon Dell
Simon Dell

Reputation: 638

CrossroadsJS doesn't actually care about the URL (in the sense of the window.location) and doesn't provide access to it. The crossroads.parse() method accepts an arbitrary string and matches against that. The string could have come from any source, URL or otherwise.

You could reverse-engineer the string using the route.interpolate() function. The function takes a hash of named values and maps them to the parameters defined in the route's match pattern. The route's handler function gets passed any matched parameters, so pass those to the hash and you should get the original string back.

Your example matches many routes, but doesn't capture the last part. Re-writing it like this should cause Crossroads to capture the final segment:

var myRoute = crossroads.addRoute( '/root/finder/:optional:', finderHandler );

You should them be able to recover the string with a handler like this:

function finderHandler ( optionalSegment ) {
   var urlFragment = myRoute.interpolate({optional: optionalSegment});
   console.log( urlFragment );
}

Upvotes: 0

Related Questions