Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save michaelkoper/9402728 to your computer and use it in GitHub Desktop.
Save michaelkoper/9402728 to your computer and use it in GitHub Desktop.
hijack links for pushState in Backbone. With open in new tab functionality.
// Use absolute URLs to navigate to anything not in your Router.
var openLinkInTab = false;
// Only need this for pushState enabled browsers
if (Backbone.history && Backbone.history._hasPushState) {
$(document).keydown(function(event) {
if (event.ctrlKey || event.keyCode === 91) {
openLinkInTab = true;
}
});
$(document).keyup(function(event) {
openLinkInTab = false;
});
// 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 (!openLinkInTab && 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);
}
});
}
@inca
Copy link

inca commented Apr 3, 2014

Typo?

  $(document).keyup(event) {
    openLinkInTab = false;
  });

@rchrd2
Copy link

rchrd2 commented Apr 24, 2014

@inca I noticed this too. Correct code:

$(document).keyup(function(event) {
    openLinkInTab = false;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment