All Projects → aknuds1 → staterouter.js

aknuds1 / staterouter.js

Licence: other
Simple JavaScript HTML5 routing library built on top of History.js

Programming Languages

javascript
184084 projects - #8 most used programming language
CSS
56736 projects
python
139335 projects - #7 most used programming language
HTML
75241 projects

StateRouter.js

Description

StateRouter.js is a small JavaScript library intended to extend the History.js HTML5 history library with routing capabilities.

Why

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.

Requirements

StateRouter.js requires just the History.js library.

Installation

Download lib/staterouter.js and include it in your page after History.js.

Usage

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');
});

Testing

StateRouter.js is tested through Jasmine specifications, contained in 'spec/StateRouter.js'. In order to run them, open 'specrunner.html' in a browser.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].