-
-
Save hadifarnoud/95dfe0d7d853aa51baa6051d4e049ada to your computer and use it in GitHub Desktop.
Hijack in-site links for Backbone.js
This file contains 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
// Use the router(s) for any internal (relative) links, unless it has a | |
// `data-bypass` attribute or is `target=_blank` | |
$(document).on('click', 'a:not([data-bypass],[target])', function(evt) { | |
var href = $(this).attr('href'), | |
protocol = this.protocol + '//'; | |
// For <a href="#"> links, we always want to preventDefault to avoid having to do | |
// this within each individual Backbone View event function. | |
// (However don't preventDefault on #something URLs in case we need to jump down a page.) | |
if (href === '#') { | |
evt.preventDefault(); | |
} | |
// Don't break cmd-click (windows: ctrl+click) opening in new tab | |
if (evt.metaKey || evt.ctrlKey) { | |
return; | |
} | |
// Ensure the protocol is not part of URL, meaning it's relative. | |
// We also don't want to do anything with links that start with "#" since we use push state | |
if (href && href.slice(0, protocol.length) !== protocol && | |
href.indexOf('#') !== 0 && | |
href.indexOf('javascript:') !== 0 && | |
href.indexOf('mailto:') !== 0 && | |
href.indexOf('tel:') !== 0 | |
) { | |
// Stop the default event to ensure the link will not cause a page | |
// refresh. | |
evt.preventDefault(); | |
// `Backbone.history.navigate` is sufficient for all Routers and will | |
// trigger the correct events. The Router's internal `navigate` method | |
// calls this anyways. | |
Backbone.history.navigate(href, true); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment