How to access router globally in js trunk?

This is my app.js. file I need to access the router navigate method from the navigateToLogin method of the LandingView class. But since appRouter is defined after the view, it cannot recognize the router from within the view. Therefore, 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(); 
+7
source share
2 answers

If you dig in the Backbone code a bit, you will notice that the implementation of the navigate router 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 removing the global scope, use Backbone.history.navigate :

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

If you want appRouter be globally accessible, you must attach it to some global object. In web browsers, this is a window object.

 window.app = new appRouter(); 

And access to it through the window:

 window.app.navigate(...); 

Using global variables can make code difficult to maintain. If your application does not have a trivial size, consider using a decoupling mechanism, such as an intermediary template .

+7
source

All Articles