Skip to content
This repository has been archived by the owner on Jan 29, 2024. It is now read-only.

Commit

Permalink
Merge pull request #26 from jmeas/array-params
Browse files Browse the repository at this point in the history
Support multiple query parameters of the same value.
  • Loading branch information
jamesplease committed Feb 25, 2015
2 parents 35a7c3a + 893a5b1 commit a0bf1a4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 14 deletions.
39 changes: 27 additions & 12 deletions src/backbone.base-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

// This is copied over from Backbone, because it doesn't expose it
var NAMED_PARAM = /(\(\?)?:\w+/g;
// Find query parameters
var QUERY_PARAMS = /([^&=]+)=?([^&]*)/g;
// Find plus symbols
var PLUS_SYMBOL = /\+/g;

Expand Down Expand Up @@ -80,16 +78,33 @@ Backbone.BaseRouter = Backbone.Router.extend({
_getQueryParameters: function(queryString) {
if (!queryString) { return {}; }

var match, urlParams = {};
while (match = QUERY_PARAMS.exec(queryString)) {
urlParams[this._decodeParams(match[1])] = this._decodeParams(match[2]);
}
return urlParams;
},

_decodeParams: function (queryString) {
// Replace addition symbol with a space
return decodeURIComponent(queryString.replace(PLUS_SYMBOL, ' '));
return _.reduce(queryString.split('&'), function(memo, param) {
var parts = param.replace(PLUS_SYMBOL, ' ').split('=');
var key = parts[0];
var val = parts[1];

key = decodeURIComponent(key);
val = val === undefined ? null : decodeURIComponent(val);

// If we don't have the value, then we set it.
if (!memo[key]) {
memo[key] = val;
}

// Otherwise, if we have the value, and it's an array,
// then we push to it.
else if (_.isArray(memo[key])) {
memo[key].push(val);
}

// Otherwise, we have a value that is not yet an array,
// so we convert it to an array, adding the newest value.
else {
memo[key] = [memo[key], val];
}

return memo;
}, {});
},

// Returns the named parameters of the route
Expand Down
4 changes: 2 additions & 2 deletions test/unit/base-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ describe('Base Router', function() {
});

it('should pass the parsed query params, not parsing the array-like syntax', function() {
expect(this.routeData.query).to.deep.equal({letters: 'c'});
expect(this.routeData.query).to.deep.equal({letters: ['a', 'b', 'c']});
});

it('should pass an empty object for named params', function() {
Expand Down Expand Up @@ -336,7 +336,7 @@ describe('Base Router', function() {
});

it('should pass the parsed query params, not parsing the array-like syntax', function() {
expect(this.routeData.query).to.deep.equal({letters: 'c'});
expect(this.routeData.query).to.deep.equal({letters: ['a', 'b', 'c']});
});

it('should pass an empty object for named params', function() {
Expand Down

0 comments on commit a0bf1a4

Please sign in to comment.