A simple and multi-purpose router with history management.
npm install highway
Require and initialize highway:
var Highway = require("highway"),
highway = new Highway();
Add a route:
var handle = highway.set("route", function routeHandler() {
// Do something when navigating to route
// this === scope;
}, scope /* optional */);
Remove a route :
highway.unset(handle);
Navigate to a route:
// this will call the handler that's defined for route with all of the following params
highway.navigate("route", "param1", "param2", {}, ...);
Watch for route changes:
var handle = highway.watch(function routeChangeHandler(newRoute, param1, param2, ...) {
// newRoute is the route that we navigated to
// scope === this;
}, scope /* optional */);
Stop watching for route changes:
highway.unwatch(handle);
Navigate in the history:
// Go back in the history, we reload the previous route with the same params.
highway.back();
// Go forward
highway.forward();
// Go back 3 times
highway.go(-3);
// Go forward 2 times
highway.get(-2);
Increase the saved history (10 by default):
// Save the last 100 routes
highway.setMaxHistory(100);
clear history
highway.clearHistory();
This a very simple router. You can build on top it if you want it to be URL based for instance:
function URLRouter() {
var highway = new Highway();
function getRouteFromUrl(url) { return ... }
function getParamsFromUrl(url) { return ... }
this.navigate = function (url) {
var route = getRouteFromUrl(url),
params = getParamsFromUrl(url);
highway.navigate.apply(highway, route, params);
};
...
}
You could also bind it to hashchange:
function HashRouter() {
var highway = new Highway();
function getRouteFromHash(hash) { return ... }
function getParamsFromHash(hash) { return ... }
window.addEventListener("hashchange", function () {
var route = getRouteFromHash(window.location.hash),
params = getParamsFromHash(window.location.hash);
highway.navigate.apply(highway, route, params);
}, true);
...
}
- Can now navigate to non-registered routes. They will be saved in the history and trigger the watch() callback.
- API clean-up with private functions not revealed in the public API anymore.
- Add specs for setMaxHistory
- Rename constructor to HighwayConstructor
- Rewrote tests to make them easier to read
- Update to watch-notify 0.0.3
MIT