这是我的 app.js 文件。我需要从 LandingView
类的 navigateToLogin
方法中访问路由器的 navigate
方法。但是由于 appRouter 是在 View 之后定义的,因此它无法从 View 中识别路由器。所以我需要找到一种从任何类或方法全局访问路由器的方法。我怎样才能解决这个问题?
var LandingView = Backbone.View.extend({
tagName: 'div',
id: 'landing',
className: 'landingpad',
events: {
'click button#login': 'navigateToLogin',
},
render: function (){
(this.$el).append("<button class='button' id='login'>Login</button><br/><br/><br/>");
(this.$el).append("<button class='button' id='new'>New User?</button>");
console.log(this.el);
return this;
},
navigateToLogin: function(e){
app.navigate("/login", true);
return false;
},
});
var appRouter = Backbone.Router.extend({
initialize: function(){
$('#content').html(new LandingView().render().el);
}
});
app = new appRouter();
最佳答案
如果你深入研究 Backbone 的代码,你会注意到路由器对 navigate
的实现依次调用 Backbone.history.navigate
:
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
}
因此,不要显式地破坏全局范围,而是使用 Backbone.history.navigate
:
var LandingView = Backbone.View.extend({
...
navigateToLogin: function(e){
Backbone.history.navigate("/login", true);
return false;
},
});
关于javascript - 如何在 Backbone js中全局访问路由器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13953080/