jQuery routes - Routing in javascript
Include the jQuery library and the jquery.routes.js file.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.routes.js"></script>
Link routes to javascript functions. Make sure the functions prepare the ui for this state of the application. Remember that you can go directly to a route without visiting the main route.
<script type="text/javascript">
var newsModule = {
fetch: function() {
$('#news').load('news.php?id=' + this.id).show();
}
fetchAll: function() {
$('#news').load('news.php').show();
}
};
$.routes.add('/news/{id:int}/', newsModule.fetch);
$.routes.add('/news/', newsModule.fetchAll);
</script>
or anonymous functions
<script type="text/javascript">
$.routes.add('/news/{id:int}/', function() {
$('#news').load('news.php?id=' + this.id).show();
});
</script>
Parameters are defined with curly braces. The syntax is {name:datatype}. The datatype can be int, float, word, date or you can create your own.
Datatypes are added in
Named routes
<script type="text/javascript">
// register the route
$.routes.add('/news/{when:date}/', 'newsByDate', function() {
alert('loading news from ' + this.when);
});
$('#get-news').click(function() {
// change the url to this route (with this date as parameter)
$.routes.find('newsByDate').routeTo({
when: new Date(2010, 1, 19);
});
});
</script>
Use routeTo function to change the url or use execute function to only execute the function for that route.
Tests are written using QUnit. The tests are running on testswarm that automatically gets new version on git commit. To help me test different browsers and operating systems, please go to my testswarm and run the tests.