Router in JavaScript Application Design

Definition and Role of a Router

In the context of MVC (Model-View-Controller) applications, a router is a crucial component that matches URL patterns to controller actions based on predefined rules. It captures incoming requests and delegates them to the appropriate controller. The controller then validates the request, decides on a view, and performs necessary actions such as rendering or redirecting.

Routers in Backbone.js

Overview

In Backbone.js, routers play a significant role in managing application state by mapping URLs to actions. This is particularly useful for single-page applications (SPAs), as it allows for changing the URL and triggering actions without reloading the page. Routers listen for URL changes and trigger corresponding actions, enabling dynamic navigation and state management.

Adding and Defining Routes

Adding routers in Backbone involves defining routes that map specific URLs to actions. For example, a router can be set up to handle different URL patterns and trigger corresponding actions:

var Backbone = require('backbone');

module.exports = Backbone.Router.extend({
  routes: {
    '': 'root',
    'items': 'items',
    'items/:id': 'getItemById'
  }
});

In this setup, visiting the application root redirects users to the items route, ensuring they are not left stranded at the root level.

Example of a Router

Consider a router that matches URL patterns to controller actions. For instance, a request for /articles/{slug} is routed through the Articles controller, invoking the getBySlug action with the slug parameter. The router evaluates rules in sequence, ignoring requests that don't match any pattern.

Instantiating and Starting a Router

To start monitoring the URL for changes, instantiate a view router and use Backbone.history.start:

var ViewRouter = require('./routers/viewRouter.js');
new ViewRouter();

$(function () {
  Backbone.history.start();
});

This setup checks the current URL to see if it matches any defined routes and triggers the appropriate route.

Testing Routers

Testing routers involves ensuring that routes and their handlers are correctly defined and invoked. The following listing demonstrates how to test a router using proxyquireify, sinon, and tape:

Testing the Module

Listing 8.28. Testing the module

var Backbone = require('backbone');
var ListView = require('../views/list.js');
var AddItemView = require('../views/addItem.js');

module.exports = Backbone.Router.extend({
  routes: {
    '': 'root',
    'items': 'listItems',
    'items/add': 'addItem'
  },

  root: function () {
    this.navigate('items', { trigger: true });
  },
  listItems: function () {
    new ListView();
  },
  addItem: function () {
    new AddItemView();
  }
});

Testing Route Handlers Individually

Listing 8.31. Testing route handlers individually

test('route # redirects to the #items route', function (t) {
  // Arrange
  var ViewRouter = getStubbedRouter();

  // Act
  var router = new ViewRouter();
  var handler = getRouteHandler(router, '');
  router.navigate = sinon.spy();
  handler();

  // Assert
  t.ok(router.navigate.calledOnce, 'called router.navigate');
  t.ok(router.navigate.calledWith('items', { trigger: true }), 'called router.navigate with proper arguments');
  t.end();
});

test('route #items renders ListView', function (t) {
  // Arrange
  var ViewRouter = getStubbedRouter();

  // Act
  var router = new ViewRouter();
  var handler = getRouteHandler(router, 'items');
  handler();

  // Assert
  t.ok(ListView.calledOnce, 'called ListView once');
  t.ok(ListView.calledWithNew(), 'called new ListView()');
  t.end();
});

test('route #items/add renders AddItemView', function (t) {
  // Arrange
  var ViewRouter = getStubbedRouter();

  // Act
  var router = new ViewRouter();
  var handler = getRouteHandler(router, 'items/add');
  handler();

  // Assert
  t.ok(AddItemView.calledOnce, 'called AddItemView once');
  t.ok(AddItemView.calledWithNew(), 'called new AddItemView()');
  t.end();
});

function getRouteHandler (router, route) {
  var routeHandler, key, i;
  var routes = Object.keys(router.routes);
  for (i = 0; i < routes.length; i++) {
    key = routes[i];
    if (route === key) {
      routeHandler = router.routes[key];
      return router[routeHandler].bind(router);
    }
  }
}

These tests ensure that the router correctly handles route changes and invokes the appropriate view constructors. By running these tests, developers can verify that their routing logic is functioning as expected.

FAQ (Frequently asked questions)

What happens if a request does not match any URL pattern in a router?

What happens when the root route is triggered in the Backbone router?

What actions are performed by the listItems and addItem routes in the Backbone router?