Last active
February 25, 2024 21:38
-
-
Save tbranyen/1142129 to your computer and use it in GitHub Desktop.
hijack links for pushState in Backbone
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
// 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(evt) { | |
// Get the absolute anchor href. | |
var href = { prop: $(this).prop("href"), attr: $(this).attr("href") }; | |
// Get the absolute root. | |
var root = location.protocol + "//" + location.host + Application.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. | |
evt.preventDefault(); | |
// Note by using Backbone.history.navigate, router events will not be | |
// triggered. If this is a problem, change this to navigate on your | |
// router. | |
Backbone.history.navigate(href, true); | |
} | |
}); |
GitHub never notified me of any of these comments >_> I just updated the Gist to latest version I've been using.
Shouldn't it be href.attr
in the navigate function?
@XemsDoom yes it should
You also should probably add a check whether or not someone called preventDefault on the event.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why use
href.slice(protocol.length)
instead ofhref.slice(0, protocol.length)
?If
href
ishttp://google.com
(not relative url), the previous will returngoogle.com
while the later returnhttp://
...