假设我有一个骨干路由器,如:
routes:
"" : "homepage"
"catalog/:id" : "catalogPage"
"catalog/:id/products/:id2" : "productPage"
homepage : -> doStuff()
catalogPage: (id) -> doOtherStuff()
productPage: (id, id2) -> doEvenMoreStuff()
Run Code Online (Sandbox Code Playgroud)
和功能:
executeBefore = -> console.log("hello")
Run Code Online (Sandbox Code Playgroud)
如果我希望每次调用路由并在相应的路由方法之前调用并执行executeBefore,除了在每个路由方法的开头插入对executeBefore的调用之外,还有一种简单的方法吗?
nik*_*shr 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();
Run Code Online (Sandbox Code Playgroud)
和演示http://jsfiddle.net/nikoshr/EdLzh/
自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);
}
Run Code Online (Sandbox Code Playgroud)
https://github.com/jashkenas/backbone/commit/791033dc1aab53e9e5c9366f64a854224f851231
| 归档时间: |
|
| 查看次数: |
5384 次 |
| 最近记录: |