Skip to content

Instantly share code, notes, and snippets.

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 shaneharter/c1458d8ddf504515c244 to your computer and use it in GitHub Desktop.
Save shaneharter/c1458d8ddf504515c244 to your computer and use it in GitHub Desktop.
Play nice with Backbone.history.root when attaching pushstate click handler
// Only need this for pushState enabled browsers
if (Backbone.history && Backbone.history._hasPushState) {
var $document = $(window.document);
var openLinkInTab = false;
// Links like <a href="some/thing/here"> are relative to the page.
// We want to run these links thru the router
var is_relative_to_page = function(href) {
return href.match(/^\/|(http:|https:|ftp:|mailto:|javascript:)/) === null;
};
// If a link is relative, or it contains the current history.root, consider the URL routable locally
// Unless it has a fragment. Let hrefs with a fragment continue normally
var is_routable = function(href) {
return href.indexOf("#") === -1 && (is_relative_to_page(href) || href.indexOf(Backbone.history.root) > -1);
};
$document.keydown(function(e) {
if (e.ctrlKey || e.keyCode === 91) {
openLinkInTab = true;
}
});
$document.keyup(function(e) {
openLinkInTab = false;
});
$document.on("click", "a", function(e) {
var href = $(this).attr("href");
if (is_routable(href)) {
e.preventDefault();
Backbone.history.navigate(href, true);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment