有谁知道如何使Backbone路由不区分大小写?
IE http:// localhost/Products http:// localhost/products
两者都触发产品路线
routes: {
"products": "products"
},
Run Code Online (Sandbox Code Playgroud)
根据mu太短的答案,这里是完整的路由器.谢谢你的帮助
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, "(.*?)");
return new RegExp('^' + route + '$', 'i'); // Just add the 'i'
}
});
Run Code Online (Sandbox Code Playgroud)
jbe*_*net 10
该optamd3版本Backbone.Router似乎并不具备escapeRegExp,namedParam和splatParam常量this.此外,完全取代功能更有可能在未来中断.
我通过调用重写函数解决了它,并使用它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'
},
...
});
Run Code Online (Sandbox Code Playgroud)
您可以手动绑定所有路由Backbone.Router.route(),它将接受路由作为字符串或RegExp对象:
Backbone.Router.route(/products/i, ...
Run Code Online (Sandbox Code Playgroud)
或者你可以取代这个私人的方法Backbone.Router,而子类(通过Backbone.Router.extend(),谢谢新月新鲜):
_routeToRegExp : function(route) {
route = route.replace(escapeRegExp, "\\$&")
.replace(namedParam, "([^\/]*)")
.replace(splatParam, "(.*?)");
return new RegExp('^' + route + '$');
}
Run Code Online (Sandbox Code Playgroud)
有了这个(你必须复制/扩展escapeRegExp namedParam,并且正在使用splatParamregex):
_routeToRegExp : function(route) {
route = route.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&")
.replace(/:\w+/g, "([^\/]*)")
.replace(/\*\w+/g, "(.*?)");
return new RegExp('^' + route + '$', 'i'); // Just add the 'i'
}
Run Code Online (Sandbox Code Playgroud)
在路由routes对象被添加到使用路由表Backbone.Router.route(),并且将它们转换到使用正则表达式_routeToRegExp.
以下是该_routeToRegExp方法的演示:http://jsfiddle.net/ambiguous/MDSC5/
| 归档时间: |
|
| 查看次数: |
2126 次 |
| 最近记录: |