8

这是我的 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();
4

2 回答 2

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);
}

因此,不要显式破坏全局范围,而是使用Backbone.history.navigate

var LandingView = Backbone.View.extend({
    ...
    navigateToLogin: function(e){
        Backbone.history.navigate("/login", true);
        return false; 
    },
});
于 2012-12-19T18:43:16.563 回答
7

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

window.app = new appRouter();

并通过窗口访问它:

window.app.navigate(...);

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

于 2012-12-19T13:21:21.323 回答