route.js: a history.pushState microrouter without the routing fluff.
// Microrouter based on history.pushState. | |
// All thrills, no frills. | |
// Usage: | |
// | |
// var h = urlstate(callback); | |
// h.push('#foo') | |
function urlstate(callback) { | |
// Since `history.pushState` doesn't fire `popstate`, we can use this function | |
// instead. Will update history state and call `callback` with currently | |
// showing `url`. | |
function push(fragment, title) { | |
history.pushState(null, null, fragment || window.location.pathname); | |
callback(document.location.href); | |
if (title) document.title = title; | |
return document.location.href; | |
} | |
// Same goes for `history.replaceState`. | |
function replace(fragment, title) { | |
history.replaceState(null, null, fragment || window.location.pathname); | |
callback(document.location.href); | |
if (title) document.title = title; | |
return document.location.href; | |
} | |
function onpopstate() { | |
// Fire callback whenever a true history change happens (e.g. user | |
// presses back button). | |
callback(document.location.href); | |
} | |
// Call callback on initialization, since Firefox doesn't fire `popstate` on | |
// window load. Safari does, however. It's assumed you're doing stateless | |
// routing, so a double-hit to callback on startup shouldn't hurt. | |
callback(document.location.href); | |
// Bind event listener. | |
window.addEventListener('popstate', onpopstate); | |
return { push: push, replace: replace }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment