Hashmux
A light URL hash to JavaScript function router.
Hashmux is a bit like HTTP multiplexers such as gorilla/mux, but it's client-side. Instead of routing HTTP requests, Hashmux routes changes in the hash part of the URL to JavaScript functions.
Examples
Once you've installed and included hashmux, you can create a Hashmux object and add some routes
var router = routerrouterrouter // Call router.listen() to activate the router.router
Variables
Hashmux supports more advanced routing too. The variables are given to the function as a map (well, actually an array with string keys).
{ // params["name"] // params.name} routerrouter
Variable variables
If you want to allow anything after a certain path, you can simply add a trailing slash. Everything after the trailing slash in requests is put in the params array with numeric indexes.
If you want to handle some specific paths separately, be sure to leave the more generic handler last.
{ // Request path: example.com/#/help/foo/bar // params: {0: "foo", 1: "bar"}} { // Request path: example.com/#/help/123/bar // params: {name: "123", 0: bar}} routerrouter
Changing pages and redirecting
To go to another page using JS, simply change the window.location.hash
value.
windowlocationhash = "#/products"
You can also use the History API for more precise control. To go to another page without leaving the current page in history, you can use
history// orrouter
If you just need to redirect one Hashmux path to another, you can use the handleRedirect
function in the router.
router// You can also have a function to provide the redirect targetrouter
Query parameters
Since 2.3.0, Hashmux has basic support for query parameters. Using them requires no extra configuration.
{ // Request path: example.com/#/blog/filter?search=layout&tag=qwerty&tag=dvorak query // "layout" if query query // ["qwerty", "dvorak"] query // undefined} router
Error handling
If Hashmux doesn't find any suitable path handler for a specific request path, it calls the 404 error handler. You can change and add error handlers with router.handleError(errorCode, handlerFunc)
.
The argument is an object. It will always contain the page
variable if the error was triggered from within Hashmux.
You can also trigger errors from elsewhere using router.error(errorCode, data)
router ... router