StateRouter.js is a small JavaScript library intended to extend the History.js HTML5 history library with routing capabilities.
I wasn't able to find any routing libraries for History.js that I was quite happy with, so I decided I might as well write my own. An important benefit of doing it myself is that I can ensure good test coverage. The tests are written BDD style, with the help of the excellent Jasmine framework.
StateRouter.js requires just the History.js library.
Download lib/staterouter.js and include it in your page after History.js.
function getHome() {
}
function getPersons() {
}
function getPerson(id) {
// Browser state is accessible as the this variable
if (/^.+?\?alert=true$/.test(this.url)) {
alert("What: " + this.data.what + "\nTitle: " + this.title + "\nURL: " + this.url);
}
}
var router = new staterouter.Router();
// Configure routes
router
.route('/', getHome)
.route('/persons', getPersons)
.route('/persons/:id', getPerson);
$(document).ready(function () {
// Perform initial routing
router.perform();
// Navigate to a URL, also specifying the page's data and title
router.navigate('/persons/1');
// Go back
router.back();
// Go forward
router.go(1);
// Navigate to a URL, also specifying the page's data and title
router.navigate('/persons/1?alert=true', {what: 'State'}, 'Person');
});
StateRouter.js is tested through Jasmine specifications, contained in 'spec/StateRouter.js'. In order to run them, open 'specrunner.html' in a browser.