Javascript 如何在主干js中全局访问路由器?
这是我的app.js文件。我需要从Javascript 如何在主干js中全局访问路由器?,javascript,backbone.js,singlepage,Javascript,Backbone.js,Singlepage,这是我的app.js文件。我需要从LandingView类的navigateToLogin方法中访问路由器的navigate方法。但由于appRouter是在视图之后定义的,因此它无法从视图中识别路由器。所以我需要找到一种从任何类或方法全局访问路由器的方法。我怎样才能避开这个问题 var LandingView = Backbone.View.extend({ tagName: 'div', id: 'landing', className: 'landingpad',
LandingView
类的navigateToLogin
方法中访问路由器的navigate
方法。但由于appRouter是在视图之后定义的,因此它无法从视图中识别路由器。所以我需要找到一种从任何类或方法全局访问路由器的方法。我怎样才能避开这个问题
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();
var-LandingView=Backbone.View.extend({
标记名:“div”,
id:'着陆',
类名:'landingpad',
活动:{
'单击按钮#登录':'导航登录',
},
渲染:函数(){
追加(“登录名
”;
追加(“新用户?”);
console.log(this.el);
归还这个;
},
导航登录:函数(e){
应用程序导航(“/login”,true);
返回false;
},
});
var appRouter=Backbone.Router.extend({
初始化:函数(){
$('#content').html(new LandingView().render().el);
}
});
app=新批准人();
如果需要appRouter
全局访问,则必须将其附加到某个全局对象。在web浏览器中,这是窗口
对象
window.app = new appRouter();
并通过窗口访问:
window.app.navigate(...);
使用globals可能会导致难以维护的代码。如果你的应用程序不是微不足道的,考虑使用一些解耦机制,比如.< /p> ,如果你深入研究了骨干代码,你会注意到路由器的实现<代码>导航< /代码>,依次调用<代码>主干。历史。导航< /代码>:
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
}
var LandingView = Backbone.View.extend({
...
navigateToLogin: function(e){
Backbone.history.navigate("/login", true);
return false;
},
});
因此,与其显式地破坏全局范围,不如使用主干.history.navigate
:
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
}
var LandingView = Backbone.View.extend({
...
navigateToLogin: function(e){
Backbone.history.navigate("/login", true);
return false;
},
});
嗯,我正在制作一个小应用程序,它非常易于管理,纯粹用于教育目的。成功了。谢谢:)`routes:{“”:“init”“/login:“loadLogin”,},`我的路由器似乎没有触发我的路由器的loadLogin功能。上面的说法有什么问题吗?@jaykumarak不确定,请尝试定义不带前导正斜杠的路线。无论如何,感谢您的帮助。我想可能有一些语法错误。我会调查的:)我解决了导航问题。我省略了导航函数中的斜杠,它成功了:)但是谢谢你提供的信息。有趣的是,解决问题的方法总是不止一种:)卢卡斯的答案应该是这个问题的公认答案。