Skip to content

Commit

Permalink
added complex key structure support
Browse files Browse the repository at this point in the history
ex: #foo?foo[a]=b

  {
    'foo': {
      'a': 'b'
    }
  }
  • Loading branch information
jhudson8 committed Nov 2, 2011
1 parent a01c507 commit dd43d38
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
22 changes: 21 additions & 1 deletion backbone.js
Expand Up @@ -726,6 +726,26 @@
_extractParameters : function(route, fragment) {
var params = route.exec(fragment).slice(1);

var keyPattern = /^[^\]]/; // detect a hash key pattern - a in a[b]
var valuePattern = /\[(.*)\]/; // detect a hash value pattern - b in a[b]
var setValue = function(key, value, data) {
var valueMatch = key.match(valuePattern);
if (valueMatch) {
var keyMatch = key.match(keyPattern);
if (keyMatch) {
// we have a hash structure
var key = keyMatch[0];
data[key] = data[key] || {};
var newKey = valueMatch[valueMatch.length-1];
setValue(newKey, value, data[key]);
} else {
data[key] = value;
}
} else {
data[key] = value;
}
};

// do we have an additional query string?
var match = params.length && params[params.length-1] && params[params.length-1].match(queryStringParam);
if (match) {
Expand All @@ -736,7 +756,7 @@
_.each(keyValues, function(keyValue) {
var arr = keyValue.split('=');
if (arr.length > 1 && arr[1]) {
data[arr[0]] = decodeURIComponent(arr[1]);
setValue(arr[0], decodeURIComponent(arr[1]), data);
}
});
}
Expand Down
13 changes: 13 additions & 0 deletions test/router.js
Expand Up @@ -96,6 +96,19 @@ $(document).ready(function() {
}, 10);
});

asyncTest("Router: routes (two part - query params - hash)", 6, function() {
window.location.hash = 'search/nyc/p10?a=b&b[c]=d&b[d]=e&b[e[f]]=g';
setTimeout(function() {
equals(router.query, 'nyc');
equals(router.page, '10');
equals(router.queryParams.a, 'b');
equals(router.queryParams.b.c, 'd');
equals(router.queryParams.b.d, 'e');
equals(router.queryParams.b.e.f, 'g');
start();
}, 10);
});

test("Router: routes via navigate", 2, function() {
Backbone.history.navigate('search/manhattan/p20', true);
equals(router.query, 'manhattan');
Expand Down

0 comments on commit dd43d38

Please sign in to comment.