Backbone.js Router Routes case insensitive
Does anyone know how to make the Backbone routes case insensitive?
I.E. http://localhost/Products http://localhost/products
both trigger the products route
routes: {
"products": "products"
},
Update
Based on mu is too short's answer, here is the full Router. Thanks for your help
MainRouter = Backbone.Router.extend({
routes: {
"": "home",
"products": "products"
},
initialize: function () {
Backbone.history.start({ pushState: true });
},
home: function () {
// just show the products!!
this.products();
},
products: function () {
// wire up the view.
var ps = new ProductsView({ el: '#products', collection: myCollection });
ps.render();
// fetch the collection!!
myCollection.fetch();
},
_routeToRegExp: function (route) {
route = route.replace(this.escapeRegExp, "\\$&")
.replace(this.namedParam, "([^\/]*)")
.replace(this.splatParam, "(.*?)");
开发者_JAVA百科 return new RegExp('^' + route + '$', 'i'); // Just add the 'i'
}
});
The optamd3
version of Backbone.Router
does not seem to have the escapeRegExp
, namedParam
, and splatParam
constants in this
. In addition, entirely replacing a function is more likely to break in the future.
I solved it by just calling the overridden function, and using its RegExp
:
var Router = Backbone.Router.extend({
_routeToRegExp: function(route) {
route = Backbone.Router.prototype._routeToRegExp.call(this, route);
return new RegExp(route.source, 'i'); // Just add the 'i'
},
...
});
You could bind all your routes manually with Backbone.Router.route()
, that will accept the route as a string or a RegExp object:
Backbone.Router.route(/products/i, ...
Or you could replace this private method in Backbone.Router
while subclassing (via Backbone.Router.extend()
, thank you Crescent Fresh):
_routeToRegExp : function(route) {
route = route.replace(escapeRegExp, "\\$&")
.replace(namedParam, "([^\/]*)")
.replace(splatParam, "(.*?)");
return new RegExp('^' + route + '$');
}
with this one (you'll have to copy/expand the escapeRegExp
namedParam
, and splatParam
regexes too):
_routeToRegExp : function(route) {
route = route.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&")
.replace(/:\w+/g, "([^\/]*)")
.replace(/\*\w+/g, "(.*?)");
return new RegExp('^' + route + '$', 'i'); // Just add the 'i'
}
The routes in the routes
object are added to the routing table using Backbone.Router.route()
and that converts them to regexes using _routeToRegExp
.
Here's a demo of the _routeToRegExp
approach: http://jsfiddle.net/ambiguous/MDSC5/
精彩评论