Skip to content

Instantly share code, notes, and snippets.

@bruth
Created July 1, 2014 13:09
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 bruth/692f45bd48505bb7af84 to your computer and use it in GitHub Desktop.
Save bruth/692f45bd48505bb7af84 to your computer and use it in GitHub Desktop.
Document event handler that catches links and navigates to a Backbone route if one exists.
// Route based on the URL
$(document).on('click', 'a', function(event) {
// Path of the target link
var path = this.pathname;
// Handle IE quirk
if (path.charAt(0) !== '/') path = '/' + path;
// Trim off the root on the path if present
var root = Backbone.history.root || '/';
if (path.slice(0, root.length) === root) {
path = path.slice(root.length);
}
// If this is a valid route then go ahead and navigate to it,
// otherwise let the event process normally to load the new
// location.
if (Backbone.history.navigate(path, {trigger: true})) {
event.preventDefault();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment