4

I'm using Backbone with Marionette.

I have a link <a> tag where I'm passing few parameters, how can I extract those values in other pages using Backbone?

<a href="http://localhost.com:8080/help/?name=matth&age=25&email=matt@gmail.com">View Details</a>

Address Bar url:

http://localhost.com:8080/help/?name=matth&age=25&email=matt@gmail.com 44

Using Php, this is straightforward:

$Url = $_GET['state']."#".$_GET['city']; 

How can I achieve it within my Backbone app?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Khalid
  • 457
  • 3
  • 19
  • Possible duplicate of [navigate route with querystring](http://stackoverflow.com/questions/11671400/navigate-route-with-querystring) – Emile Bergeron Feb 13 '17 at 15:59

1 Answers1

5

If the route is defined with something like this:

'help/:name&:age&:email' : 'help'

Then you can access those params in the help function just by defining them in the signature of the method (within the backbone router),

help: function(name, age, email) {
    // do whatever you want with the params
}

In your case, this will give you params like this:

name="XXX" age="XXX"

So the proper routing would be

'help/?(name=:name)(&age=:age)(&email=:email)' : 'help'

Where parentheses make a part optional.

Backbone docs

Routes can contain parameter parts, :param


Note that the order is important and the following url wouldn't trigger the route callback. Notice the email and age params placement.

help/?name=test&email=test%40example.com&age=6

In order to trigger a route regardless of the number of params and their ordering, take a look at how to parse the query string in the route function, but that won't always work.

Community
  • 1
  • 1
Ryad Boubaker
  • 1,491
  • 11
  • 16
  • 1
    Be aware that with this route, the params order is important and none are optional. They can be made optional with parentheses `help/?(name=:name)(&age=:age)` but a different ordering won't trigger the route. – Emile Bergeron Feb 14 '17 at 13:07
  • The parentheses should be in the route string, not in the URL. What I meant is that an URL like `help/?name=test&email=test%40example.com&age=6` would fail even though it's a valid URL since query string parameters order is not relevant by design. – Emile Bergeron Feb 14 '17 at 15:36