Search code examples
javascriptbackbone.jssinglepage

How to access router globally in backbone js?


This is my app.js file. I need to access the router's navigate method from within the navigateToLogin method of the LandingView class. But since the appRouter is defined after the view it can't recognize the router from within the view. So I need to find a way to globally access the router from any class or method. How can I get around this problem?

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

Solution

  • If you dig into Backbone's code a little, you'll notice that the router's implementation of navigate in turn calls Backbone.history.navigate:

    // Simple proxy to `Backbone.history` to save a fragment into the history.
    navigate: function(fragment, options) {
      Backbone.history.navigate(fragment, options);
    }
    

    So instead of explicitly mucking up the global scope, use Backbone.history.navigate:

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