public
Last active

hijack links for pushState in Backbone

  • Download Gist
backbone_pushstate_router.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Use absolute URLs to navigate to anything not in your Router.
 
// Only need this for pushState enabled browsers
if (Backbone.history && Backbone.history._hasPushState) {
 
// Use delegation to avoid initial DOM selection and allow all matching elements to bubble
$(document).delegate("a", "click", function(evt) {
// Get the anchor href and protcol
var href = $(this).attr("href");
var protocol = this.protocol + "//";
 
// Ensure the protocol is not part of URL, meaning its relative.
// Stop the event bubbling to ensure the link will not cause a page refresh.
if (href.slice(protocol.length) !== protocol) {
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);
}
});
 
}

Awesomeness! Thanks for sharing.

Thanks, Tim!

I'm using mod_rewrite to get "normal" URLs, so I also check href if it begins with #

Look out for javascript: links, too.

Thank you, really cool.

This doesn't seem to work anymore. Backbone.history._hasPushState is undefined now.

Cool. Doesn't work with anchors though. I just shoved in a

if (!href.match(/^#/)) {

before the protocol check to get it all working.

Thank you very much!!!

Thanks. This is a massive help.

Thanks a lot for this! Works great except if you are holding the cmd button to open links in a new tab

This gist seems to be close to #1 on Google when you search for backbone router links so here is the Coffeescript version https://gist.github.com/gabceb/9629965

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.