Forked from wololodev/backbone_pushstate_router.js
Last active
August 29, 2015 14:06
-
-
Save shaneharter/c1458d8ddf504515c244 to your computer and use it in GitHub Desktop.
Play nice with Backbone.history.root when attaching pushstate click handler
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
// 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