Created
February 4, 2011 21:52
-
-
Save mataspetrikas/811849 to your computer and use it in GitHub Desktop.
adding pushState support in BackBone.js (experimental)
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
// browser history with HTML5 support | |
(function() { | |
var loc = window.location, | |
pushSupport = !!(window.history && window.history.pushState), | |
hashStrip = /^#*/; | |
// add HTML5 support to Backbone.history, drop the old IE stuff | |
_.extend(Backbone.History.prototype, { | |
getFragment : function(l) { | |
l = l || window.location; | |
if (pushSupport){ | |
return l.pathname; | |
} else { | |
return l.hash.replace(hashStrip, ''); | |
} | |
}, | |
start : function() { | |
if (pushSupport) { | |
// modern browsers | |
$(window).bind('popstate', this.checkUrl); | |
} else if('onhashchange' in window) { | |
// older browsers without pushState support | |
if(loc.pathname === "/"){ | |
$(window).bind('hashchange', this.checkUrl); | |
}else{ | |
// automatically redirect browsers to the BB-readable path | |
var hashPath = "/#" + loc.pathname; | |
loc.replace(hashPath); | |
return; | |
} | |
} | |
return this.loadUrl(); | |
}, | |
saveLocation : function(fragment) { | |
fragment = (fragment || '').replace(hashStrip, ''); | |
if (this.fragment == fragment) return; | |
if(pushSupport){ | |
this.fragment = fragment; | |
history.pushState({ts: new Date()}, document.title, loc.protocol + "//" + loc.host + fragment); | |
}else{ | |
window.location.hash = this.fragment = fragment; | |
} | |
} | |
}); | |
})(); | |
// use example, on click | |
// manually set the location | |
Backbone.history.saveLocation(href); | |
// and load the url | |
Backbone.history.loadUrl(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not use https://github.com/balupton/History.js for use with Backbone? That way you can support the HTML5 features of the History API (replaceState, data and titles) so rather than just gracefully upgrading, you also gracefully downgrade.