12

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

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

4 回答 4

29

您可以覆盖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/

于 2013-04-11T08:06:12.710 回答
5

自 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

于 2015-12-29T08:14:18.730 回答
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 ){ ... }
});
于 2014-09-17T22:27:09.807 回答
-1

你可以玩事件:

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

访问 #help/uploading 将触发路由器的 route:help 事件。

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

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);
});
于 2013-04-11T08:13:22.067 回答