Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js routing when query passed to route contains /

My app basically takes some form input and returns a set of results. I have two routes

routes: {
        '': 'search',
        'search': 'search',
        'results/:query': 'results'
    },
    results: function(query) {
        var search = new ResultsSearchView();
        var grid = new GridView({ query: query });
    }

If the query contains any characters / specifically (can totally happen in this case), they are added to the URL and my route breaks.

I have tried using encodeURI() and encodeURIComponent() bit I'm not having any luck. How are you folks handling such things?

like image 393
Charles Avatar asked Oct 06 '22 18:10

Charles


1 Answers

You can use encodeURIComponent when building the URL to convert the / to %2F and then decodeURIComponent inside the route handler to convert them back; the HTML would end looking like this:

<a href="#results/pancakes">no slash</a>
<a href="#results/where%2Fis%2Fpancakes%2Fhouse">with slashes</a>

and then in the router:

routes: {
    'results/:query': 'results'
},
results: function(query) {
    query = decodeURIComponent(query);
    // Do useful things here...
}

Demo: http://jsfiddle.net/ambiguous/sbpfD/

Alternatively, you could use a splat route:

Routes can contain parameter parts, :param, which match a single URL component between slashes; and splat parts *splat, which can match any number of URL components.

So your HTML would be like this:

<a href="#results/pancakes">no slash</a>
<a href="#results/where/is/pancakes/house">with slashes</a>

and your router:

routes: {
    'results/*query': 'results'
},
results: function(query) {
    // Do useful things here...
}

Demo: http://jsfiddle.net/ambiguous/awJxG/

like image 80
mu is too short Avatar answered Oct 13 '22 09:10

mu is too short