Skip to content

Instantly share code, notes, and snippets.

@joemar-tagpuno
Forked from tbranyen/app.js
Last active August 29, 2015 14:26
Show Gist options
  • Save joemar-tagpuno/b7f5a01fc83650253950 to your computer and use it in GitHub Desktop.
Save joemar-tagpuno/b7f5a01fc83650253950 to your computer and use it in GitHub Desktop.
backbone.js sub routing
/* Pretend app setup stuff is here */
/* Kick off app */
jQuery(function($) {
var Gallery = app.module("gallery");
app.Router = Backbone.Router.extend({
initialize: function() {
this.gallery = new Gallery.Router("gallery/");
}
});
// Actually initialize
new app.Router();
});
(function(Helper) {
Helper.SubRoute = Backbone.Router.extend({
constructor: function(prefix) {
var routes = {};
// Prefix is optional, set to empty string if not passed
prefix = prefix || "";
// Allow for optionally omitting trailing /. Since base routes do not
// trigger with a trailing / this is actually kind of important =)
if (prefix[prefix.length-1] == "/") {
prefix = prefix.slice(0, prefix.length-1);
// If a prefix exists, add a trailing /
} else if (prefix) {
prefix += "/";
}
// Every route needs to be prefixed
_.each(this.routes, function(callback, path) {
if (path) {
return routes[prefix + path] = callback;
}
// 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] = callback;
});
// Must override with prefixed routes
this.routes = routes;
// Required to have Backbone set up routes
Backbone.Router.prototype.constructor.call(this);
}
});
})(app.module("helper"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment