Skip to content

Instantly share code, notes, and snippets.

@gabceb
Created March 18, 2014 21:22
Show Gist options
  • Save gabceb/9629965 to your computer and use it in GitHub Desktop.
Save gabceb/9629965 to your computer and use it in GitHub Desktop.
hijack links for pushState in Backbone using Coffeescript. Original JS code at https://gist.github.com/tbranyen/1142129
# 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", (evt) ->
# Get the anchor href and protcol
href = $(this).attr("href")
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)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment