Backbone.js Router路由不区分大小写



有人知道如何使主干路由不区分大小写吗?

即http://localhost/Productshttp://localhost/products

都触发产品路由

routes: {
    "products": "products"
},

更新

基于mu太短的答案,这里是完整的Router。谢谢你的帮助

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'
    }
});

Backbone.Routeroptamd3版本似乎没有this中的escapeRegExp, namedParamsplatParam常量。此外,完全替换一个函数在将来更有可能崩溃。

我通过调用重写的函数来解决这个问题,并使用它的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'
  },
  ...
});

你可以用Backbone.Router.route()手动绑定所有的路由,它将接受路由作为字符串或RegExp对象:

Backbone.Router.route(/products/i, ...

或者你可以在Backbone.Router中替换这个私有方法,同时子类化(通过Backbone.Router.extend(),感谢Crescent Fresh):

_routeToRegExp : function(route) {
  route = route.replace(escapeRegExp, "\$&")
               .replace(namedParam, "([^/]*)")
               .replace(splatParam, "(.*?)");
  return new RegExp('^' + route + '$');
}

使用这个(您必须复制/扩展escapeRegExp namedParamsplatParam正则表达式):

_routeToRegExp : function(route) {
  route = route.replace(/[-[]{}()+?.,\^$|#s]/g, "\$&")
               .replace(/:w+/g, "([^/]*)")
               .replace(/*w+/g, "(.*?)");
  return new RegExp('^' + route + '$', 'i'); // Just add the 'i'
}

routes对象中的路由使用Backbone.Router.route()添加到路由表中,并使用_routeToRegExp将它们转换为正则表达式。

下面是_routeToRegExp方法的演示:http://jsfiddle.net/ambiguous/MDSC5/

最新更新