Created
July 1, 2014 13:09
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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