如何在执行路由方法之前运行“中间件”功能?

时间:2013-04-11 07:01:40

标签: backbone.js

假设我有一个骨干路由器,如:

routes:
  ""                          : "homepage"
  "catalog/:id"               : "catalogPage"
  "catalog/:id/products/:id2" : "productPage"

homepage   :           -> doStuff()
catalogPage: (id)      -> doOtherStuff()
productPage: (id, id2) -> doEvenMoreStuff()

和一个功能:

executeBefore = -> console.log("hello")

如果我想在每次调用路由时和相应的路由方法之前调用并执行executeBefore,除了在每个路由方法的开头插入对executeBefore的调用之外,还有一种简单的方法吗?

4 个答案:

答案 0 :(得分:28)

您可以覆盖路由器类中的route功能来拦截路由呼叫:

var Router = Backbone.Router.extend({
    routes: {
        "" : "homepage",
        "catalog/:id" : "catalogPage"
    },

    route: function(route, name, callback) {
        var router = this;
        if (!callback) callback = this[name];

        var f = function() {
            console.log('route before', route);
            callback.apply(router, arguments);
            console.log('route after', route);
        };
        return Backbone.Router.prototype.route.call(this, route, name, f);
    },

    homepage: function() {
        console.log("homepage");
    },
    catalogPage: function(id) {
        console.log("catalogPage "+id);
    }
});

var r = new Router();
Backbone.history.start();

演示http://jsfiddle.net/nikoshr/EdLzh/

答案 1 :(得分:4)

自2014年2月13日起,您可以使用router.execute(callback, args, name)http://backbonejs.org/#Router-execute)。

所以你的拦截器看起来像这样

routes: {
    '': 'homepage',
    'catalog/:id': 'catalogPage',
    'catalog/:id/products/:id2': 'productPage'
},
execute: function(callback, args, name) {
    // Do your stuff here
    executeBefore();

    if (callback) callback.apply(this, args);
}

https://github.com/jashkenas/backbone/commit/791033dc1aab53e9e5c9366f64a854224f851231

答案 2 :(得分:2)

您也可以使用backbone.routefilter插件。

您将能够为所有路线设置过滤器

var Router = Backbone.Router.extend({
  routes: {
    "": "index",
    "page/:id": "page"
  },
  before: function( route, params ) { ... },
  after: function( route, params ) { ... },
  index: function(){ ... },
  page: function( route ){ ... }
});

或选择一些路线

var Router = Backbone.Router.extend({
  routes: {
    "": "index",
    "page/:id": "page"
  },
  before: {
    "": function( route ) { ... },
    "page/:id": function( route ) { ... }
  },
  after: function( route ) { ... },
  index: function(){ ... },
  page: function( route ){ ... }
});

答案 3 :(得分:-1)

您可以玩事件:

Backbone.history.on('route', function () {
    // Do your stuff here.
    executeBefore();
});
  

访问#help / uploaded将触发路由:来自路由器的帮助事件。

显然,这将在重定向之前触发:

https://github.com/documentcloud/backbone/blob/master/backbone.js#L1243

Backbone.history.route(route, function(fragment) {
    var args = router._extractParameters(route, fragment);
    callback && callback.apply(router, args);
    router.trigger.apply(router, ['route:' + name].concat(args));
    router.trigger('route', name, args);
    Backbone.history.trigger('route', router, name, args);
});