Skip to content

Commit

Permalink
Add an optional argument 'trailingSlashIsSignificant' to Backbone.Rou…
Browse files Browse the repository at this point in the history
…ter so application authors can determine whether their applications treats URIs with a trailing slash as a different resource than URIs without a trailing slash. Defaults to true. This option causes Router to set the 'routeTrailingSlashPattern' variable, which is added to the overall URIs matching regex. jashkenas#848
  • Loading branch information
Aaron Holmes committed Apr 24, 2014
1 parent c8f8830 commit 08c5cab
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
7 changes: 6 additions & 1 deletion backbone.js
Original file line number Diff line number Diff line change
Expand Up @@ -1285,6 +1285,9 @@
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
if ('trailingSlashIsSignificant' in options) {
routeTrailingSlashPattern = options.trailingSlashIsSignificant ? '' : '[/]?';
}
this._bindRoutes();
this.initialize.apply(this, arguments);
};
Expand All @@ -1295,6 +1298,7 @@
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
var routeTrailingSlashPattern = '';

// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
Expand Down Expand Up @@ -1361,7 +1365,8 @@
return optional ? match : '([^/?]+)';
})
.replace(splatParam, '([^?]*?)');
return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');

return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?' + routeTrailingSlashPattern + '$');
},

// Given a route, and a URL fragment that it matches, return the array of
Expand Down
23 changes: 23 additions & 0 deletions test/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,29 @@
equal(lastArgs[0], 'news');
});

test("routes (simple, trailing slash is significant)", 4, function() {
location.replace('http://example.com#search/news/');
Backbone.history.checkUrl();
equal(typeof router.query, 'function');
equal(router.page, void 0);
equal(lastRoute, 'anything');
equal(lastArgs[0], 'search/news/');
});

test("routes (simple, trailing slash is insignificant)", 4, function() {
location.replace('http://example.com#search/news/');
Backbone.history.stop();
Backbone.history = _.extend(new Backbone.History, {location: location});
var route = new Router({ trailingSlashIsSignificant : false });
Backbone.history.on('route', onRoute);
Backbone.history.start();
Backbone.history.checkUrl();
equal(route.query, 'news');
equal(route.page, void 0);
equal(lastRoute, 'search');
equal(lastArgs[0], 'news');
});

test("routes (simple, but unicode)", 4, function() {
location.replace('http://example.com#search/тест');
Backbone.history.checkUrl();
Expand Down

0 comments on commit 08c5cab

Please sign in to comment.