如何在骨干网中全局访问路由器?

jay*_*ark 8 javascript singlepage backbone.js

这是我的app.js文件.我需要访问路由器的navigate距离内方法navigateToLogin的方法LandingView类.但由于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();
Run Code Online (Sandbox Code Playgroud)

Luk*_*kas 20

如果你稍微深入研究一下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);
}
Run Code Online (Sandbox Code Playgroud)

因此,不要明确地删除全局范围,而是使用Backbone.history.navigate:

var LandingView = Backbone.View.extend({
    ...
    navigateToLogin: function(e){
        Backbone.history.navigate("/login", true);
        return false; 
    },
});
Run Code Online (Sandbox Code Playgroud)


jev*_*lio 7

如果需要appRouter全局访问,则必须将其附加到某个全局对象.在Web浏览器中,这是window对象.

window.app = new appRouter();
Run Code Online (Sandbox Code Playgroud)

并通过窗口访问它:

window.app.navigate(...);
Run Code Online (Sandbox Code Playgroud)

使用全局变量可能会导致代码难以维护.如果您的应用程序不是很小,请考虑使用一些解耦机制,例如中介模式.