Skip to content

Instantly share code, notes, and snippets.

@ssafejava
Last active January 3, 2016 02:19
Show Gist options
  • Save ssafejava/8394497 to your computer and use it in GitHub Desktop.
Save ssafejava/8394497 to your computer and use it in GitHub Desktop.
Backbone link hijacking
// All navigation that is relative should be passed through the navigate
// method, to be processed by the router. If the link has a `data-bypass`
// attribute, bypass the delegation completely.
$(document).on('click', 'a[href]:not([data-bypass])', function(ev) {
// Get the absolute anchor href.
var $link = $(ev.currentTarget);
var href = { prop: $link.prop("href"), attr: $link.attr("href") };
// Get the absolute root.
var root = location.protocol + "//" + location.host + app.root;
// Ensure the root is part of the anchor href, meaning it's relative.
if (href.prop.slice(0, root.length) === root) {
// Stop the default event to ensure the link will not cause a page
// refresh.
ev.preventDefault();
// `Backbone.history.navigate` is sufficient for all Routers and will
// trigger the correct events. The Router's internal `navigate` method
// calls this anyways. The fragment is sliced from the root.
Backbone.history.navigate(href.attr, true);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment