我如何运行"中间件"路由方法之前函数执行? [英] How can I run a "middleware" function before a route method is executed?
本文介绍了我如何运行"中间件"路由方法之前函数执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个骨干路由器,如:
Say I have a backbone router like:
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打电话做分开?
If I want executeBefore to be called and executed each time a route is called and before the corresponding route method, is there a simple way to do it apart from inserting a call to executeBefore at the beginning of every route method ?
推荐答案
您可以覆盖路线
功能在你的路由器类拦截路由呼叫:
You can override the route
function in your router class to intercept the route calls :
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/
这篇关于我如何运行"中间件"路由方法之前函数执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文