只是想知道是否有一种简单的方法可以在每次使用 Backbone.js 路由器时触发自定义函数,而不必将其添加到每个路由器函数中。现在我的脚本看起来像这样:
var AppRouter = Backbone.Router.extend({
routes: {
'' : 'index',
'test': 'test',
},
initialize: function() {
},
index: function() {
customFunction();
indexView.render();
},
test: function() {
customFunction();
testView.render();
},
});
我想要这样的东西:
var AppRouter = Backbone.Router.extend({
routes: {
'' : 'index',
'test': 'test',
},
initialize: function() {
},
index: function() {
indexView.render();
},
test: function() {
testView.render();
},
change: function() {
customFunction();
}
});
有人有什么建议吗?
最佳答案
每当路由被 Router
匹配时,一个 route:[name]
事件就会被触发,并带有匹配的路由名称,以允许类监听特定的路线匹配。所有主干对象还支持 all
事件,只要有事件发生就会触发。
因此,您可以利用它绑定(bind)到 Router
上的 all
事件,只要路由器执行某些路由,该事件就会触发。
initialize: function() {
this.bind( "all", this.change )
},
如果您对匹配的路由感兴趣,它会作为第一个参数传递给绑定(bind)函数。
更多详情 here in the FAQ
关于javascript - 每次使用 Router 时 Backbone.js 触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9704086/