How to use Crossroads.js? A tutorial with examples

Are you making a Single Page Application  or an SPA ? And Do you want to update the URL of the page without reloading the page? Do you want your page to respond to the change in the URL without reloading the page? In Short, if you are looking for a javascript routing library then you might be interested in Crossroads.js!

What is Crossroads.js ?

In simple terms, Crossroads.js is a JavaScript based routing library. This means you can use it to track the change/update in the URL and call specific modules/methods/functions for specific URLs/URL patterns. You can do vice versa too, wherein you can update the path when you call a specific function/method. Usually, in SPA-based libraries/frameworks like ReactJs or Angular, you would have used routers that either comes inbuilt or installed using a 3rd party package.

Let’s look at the description of Crossroads given by its author Miller Medeiros :

Crossroads.js is a routing library inspired by URL Route/Dispatch utilities present on frameworks like Rails, Pyramid, Django, CakePHP, CodeIgniter, etc… It parses a string input and decides which action should be executed by matching the string against multiple patterns.

Getting started with CrossroadsJs – A Javascript client-side router

Step 1 :
Firstly, you need to include Js-Signals on your page before you include CrossroadsJs because it has a dependency on js-signals. If required the dependency can be removed easily by tweaking the CrossroadsJs file.

Step 2 :
Secondly, include the Crossroads.js file on your page.

By now your page should have something similar to this :

<script type="text/javascript" src="js/js-signals.js"></script>
<script type="text/javascript" src="js/crossroads.js"></script>

Step 3 :
Now the next step is to define a route in CrossroadsJs

How to add a route in CrossroadsJs?

You can add a route in CrossroadsJs by using the crossroads.addRoute() API. The syntax for the API is :

crossroads.addRoute(pattern, [handler], [priority])

The pattern parameter can be string or a reg-exp. It can contain variables wrapped within ‘ {} ‘. Each pattern string is delimited using the ” / “. Which means that the pattern ” {page}/{method} ” might match “product/add” but will not match “product/edit/foo”.

The handler is the function to be called after the URL matches a pattern. Let’s take a look at an example:

var default_routes = crossroads.addRoute("product/{id}",function(id){
				goToProduct(id);// The function that you would like to call when somebody hits a url like yoursite.com/product/123
		});

In the above example, the 2nd parameter is the handler function. You can notice that the parameters that we defined in the pattern can be passed on to the Handler too.

The third Parameter Priority is used to define the priority to be considered during the parsing of the routes. By default, the pattern tests stop the moment a pattern is matched. You can override it using the Priority parameter. This has to be an integer.

The entry point for CrossroadsJs

Now that your routes are defined and your Handler functions are written, you need to initiate the CrossroadsJs parser as the page loads. Actually, it is wise to have an init function which would be the first function called on your page, and within that init you can have the CrossroadsJs parser called. Let’s take a look at an example.

function init() {
    var productRoutes = crossroads.addRoute("product/{id}", function (id) {
        goToProduct(id);
    });

    var default_routes = crossroads.addRoute("/{source}", function (source) {
        goToPage(source);
    });

    crossroads.parse(document.location.pathname); /*This is where the parser function is called to match against the routes defined*/
}

In the example above you can notice that there are routes defined and on line 10 the crossroads.parse() function is called with document.location.pathname as the parameter. The crossroads.parse() function basically tells Crossroads to parse and match the string parameter passed against the routes defined. So the moment crossroads.parse() is called, it matches the parameter string against the routes defined, and as it finds a match it stops looking further and executes the handler function defined in the routes declaration.

There are many other APIs that CrossroadsJs provides. You can read more about CrossroadsJs at http://millermedeiros.github.io/crossroads.js/ . Hope you would like CrossroadsJs.

Do let us know about your thoughts and experiences. Also please do like us on Facebook. You may also follow us on Twitter for interesting Tips and Tricks. Also please do share the post with your friends if you liked it !

2 thoughts on “How to use Crossroads.js? A tutorial with examples”

  1. Have you had any success using crossroads and setting the page title? I’ve tried using document.title or $(document).(‘title’) but both seem to induce wacky states on the browser history stack.

    Thanks,
    Jonathan

Comments are closed.