Last active
April 30, 2022 01:26
-
-
Save gordonbrander/62eb1076febbde1576b0 to your computer and use it in GitHub Desktop.
route.js: a history.pushState microrouter without the routing fluff.
This file contains hidden or 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
// 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
Very nice... License?