Blog of Raivo Laanemets

Router renamed to hash-regex-router and upgraded


I have upgraded my client-side router package "router" and renamed it to hash-regex-router. All changes are backwards-compatible. One important issue got fixed.

I extracted the package 2 years ago from the code that I was using for client-side routing in KnockoutJS applications. The code was really minimal, especially after throwing away setInterval-based polling and solely relying on load and hashchange events.

window.location.hash encoding

The longstanding issue in the router was inconsistent behavior of parsing the current URL fragment. Whether the fragment is URL-encoded or not, depends on the browser. The general issue and possible solutions are documented in a StackOverflow thread. Fortunately there is a cross-browser solution (parsing window.location.href) and the router uses it now.

Lifecycle API

The router can now be enabled/disabled with enable() and disable() methods. The router is enabled by default. The new leave callback allows to intercept when the current route is about to change. It can be used as:

route.leave = function() {
    return confirm('Leave the current route?');
};

The callback is automatically removed when the function returns true. The implementation for the leave callback was not simple, as the browser's hashchange event is not cancellable. The implementation gets the new hash but restores the old one (and prevents re-routing on restore) when the callback returns false.

Support

The library supports all browsers starting with IE9. Installation can be done from NPM (npm install hash-regex-router). CommonJS/AMD/vanilla browser environments are supported. Source code/documentation/issues are on GitHub.


Comments

No comments have been added so far.

Email is not displayed anywhere.
URLs (max 3) starting with http:// or https:// can be used. Use @Name to mention someone.