The only option that comes to my mind is to overwrite the current Router.route function, currently it looks like this :
route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (!callback) callback = this[name]; // this is of interest Backbone.history.route(route, _.bind(function(fragment) { var args = this._extractParameters(route, fragment); callback && callback.apply(this, args); this.trigger.apply(this, ['route:' + name].concat(args)); Backbone.history.trigger('route', this, name, args); }, this)); return this; },
What you want to do is wrap each callback with a function that checks to see if the condition you want is met and then either bypasses or redirects to login. The underline wrap function is useful here.
route: function(route, name, callback) { ... // same as above if (!callback) callback = this[name]; _.wrap(callback, function(cb) { if (userIsLoggedIn()) { cb(); } else { this.navigate("url/to/login"); } }); ... // same as above },
Of course, you need to add a check for the actual entry route so that you don't create an infinite loop!
EDIT:
You do not need to change the source, the easiest way to do this:
var CustomRouter = Router.extend({ route: function() {
Use this over the comment as it is native to Backbone!
Hope this helps
jakee source share