tiny-hash-router

0.1.5 • Public • Published

HashRouter.js

Super simple URL dispatcher for single page apps.

Why?

I wrote some URL dispatchers for server-side apps in the past. When I started writing single-page apps (with my API-server) I needed a simple way of registering URL routes (to sort-of preserve state in the application after refresh).

All the routes are attached in the hash (document.location.hash).

Installation

npm/webpack

npm install --save tiny-hash-router

Bower

bower install --save HashRouter

How?

var hRouter = new HashRouter.Router;
hRoute.route("foo/bar/:page", function(page) {
  console.error("foo/bar on page", page);
}).name("my_route").setDefault("page", 1);
 
hRoute.route("list/:table/:page", function(table, page) {
});
 
hRoute.addFilter('page', function(page) {
    return parseInt(page) >= 1;
});
 
hRoute.registerListener(); // do the initial route.
 
console.error(hRoute.url("my_page", 99));

Or you can use it directly with WebPack.

import Router from 'tiny-hash-router'

let hRoute = new Router;
hRoute.route("foo/bar/:page", function(page) {
  console.error("foo/bar on page", page);
}).name("my_route").setDefault("page", 1);

hRoute.route("list/:table/:page", function(table, page) {
});

hRoute.addFilter('page', function(page) {
    return parseInt(page) >= 1;
});

hRoute.registerListener(); // do the initial route.

console.error(hRoute.url("my_page", 99));

The library will listen to any change in the document.location.hash, and any change will trigger the newer action.

Disclaimer

  1. This is a work in progress, and things will be added
  2. Things to add in the near future:
  3. Catch-all routes
  4. Events
  5. Pre-routes
  6. Post-routes
  7. Clean up (after we "leave" a given URL).
  8. Better support for RegExp

Package Sidebar

Install

npm i tiny-hash-router

Weekly Downloads

1

Version

0.1.5

License

ISC

Last publish

Collaborators

  • crodas