Skip to content

Instantly share code, notes, and snippets.

@geekdave
Created April 5, 2012 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geekdave/2314704 to your computer and use it in GitHub Desktop.
Save geekdave/2314704 to your computer and use it in GitHub Desktop.
backbone.subroute extends the functionality of Backbone.Router such that each of an application's modules can define its own module-specific routes.
// improved backbone subrouting.
// based on tim branyan's gist: https://gist.github.com/1235317
if ( !this.Backbone ) {
throw new Error( 'Error: backbone.js must be included before this file' );
}
Backbone.SubRoute = Backbone.Router.extend( {
constructor:function ( prefix ) {
var routes = {};
// Prefix is optional, set to empty string if not passed
this.prefix = prefix = prefix || "";
// Allow for optionally omitting trailing /. Since base routes do not
// trigger with a trailing / this is actually kind of important =)
if ( prefix.substr( -1 ) != "/" ) {
prefix = prefix + '/';
}
// Every route needs to be prefixed
_.each( this.routes, function ( callback, path ) {
if ( path ) {
routes[prefix + path] = callback;
} else {
// If the path is "" just set to prefix, this is to comply
// with how Backbone expects base paths to look gallery vs gallery/
routes[prefix.substr( 0, prefix.length - 1 )] = callback;
}
} );
// Must override with prefixed routes
this.routes = routes;
// Required to have Backbone set up routes
Backbone.Router.prototype.constructor.call( this );
// we've just setup subroutes for *future* changes to the URL. but now,
// we need to check if the *current* URL already has a subroute that we
// should do something with, so grab the full URL of the browser...
var hash = Backbone.history.getHash();
// check if there is already a part of the URL that this subview cares about...
var hashPart = hash.substr( prefix.length, hash.length );
// ...if so, trigger the subroute immediately. this supports the case where
// a user directly navigates to a URL with a subroute on the first page load.
if ( hashPart && hashPart != "" ) {
Backbone.history.loadUrl( prefix + hashPart );
}
},
navigate:function ( route, options ) {
if ( route.substr( 0, 1 ) != '/' && route.indexOf( this.prefix.substr( 0, this.prefix.length - 1 ) ) != 0 ) {
route = this.prefix + route;
}
Backbone.Router.prototype.navigate.call( this, route, options );
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment