Chaplin.Router → Source

This module is responsible for observing URL changes and matching them against a list of declared routes. If a declared route matches the current URL, a router:match event is triggered.

Chaplin.Router is a replacement for Backbone.Router and does not inherit from it. It is a stand-alone implementation with several advantages over Backbone’s default. Why change the router implementation completely?

In Backbone there are no controllers. Instead, Backbone’s Router maps routes to its own methods, serving two purposes and being more than just a router. Chaplin on the other hand delegates the handling of actions related to a specific route to controllers. Consequently, the router is really just a router. While the router has been rewritten for this purpose, Chaplin is using Backbone.History in the background. That is, Chaplin relies upon Backbone for handling hash URLs and interacting with the HTML5 History API (pushState).

Declaring routes in the routes file

By convention, all application routes should be declared in a separate file, the routes module. This is a simple module in which a list of match statements serve to declare corresponding routes. For example:

match '', 'home#index'
match 'likes/:id', controller: 'controllers/likes', action: 'show'
match('', 'home#index');
match('likes/:id', {controller: 'controllers/likes', action: 'show'});

Ruby on Rails developers may find match intuitively familiar. For more information on its usage, see below. Internally, route objects representing each entry are created. If a route matches, a router:match event is published, passing the route object and a params hash which contains name-value pairs for named placeholder parts of the path description (like id in the example above), as well as additional GET parameters.

Methods

createHistory()

Creates the Backbone.History instance.

startHistory()

Starts Backbone.History instance. This method should be called only after all routes have been registered.

stopHistory()

Stops the Backbone.History instance from observing URL changes.

match([pattern], [target], [options={}])

Connects a path with a controller action.

The pattern argument may contain named placeholders starting with a colon (:) followed by an identifier. For example, 'products/:product_id/ratings/:id' will match the paths /products/vacuum-cleaner/ratings/jane-doe as well as /products/8426/ratings/72. The controller action will be passed the parameter hash {product_id: "vacuum-cleaner", id: "jane-doe"} or {product_id: "8426", id: "72"}, respectively.

The target argument is a string with the controller name and the action name separated by the # character. For example, 'likes#show' denotes the show action of the LikesController.

You can also equivalently specify the target via the action and controller properties of the options hash.

The following properties of the options hash are recognized:

route([path])

Route a given path manually. Returns a boolean after it has been matched against the registered routes, corresponding to whether or not a match occurred.

This looks similar to Backbone.history.loadUrl, but it accepts an absolute path with a leading slash (e.g. /foo) and passes a changeURL parameter to the route handler function.

routeHandler([path], [callback])

Handler for the global !router:route event, performs routing for the path given in path. If callback is provided, it will be called with a boolean value communicating whether or not there was a match.

changeURL([url])

Changes the current URL and adds a history entry without triggering any route actions.

changeURLHandler([url])

Handler for the globalized !router:changeURL event. Calls this.changeURL.

dispose()

Stops the Backbone.history instance and removes it from the router object. Also unsubscribes any events attached to the Router. On compliant runtimes, the router object is frozen, see Object.freeze.

Global events of Chaplin.Router

Chaplin.Router listens to these global events:

Usage

Chaplin.Router is a dependency of Chaplin.Application which should be extended by your main application class. Within your application class you should initialize the Router by calling this.initRouter, passing your routes module as an argument.

define [
  'chaplin',
  'routes'
], (Chaplin, routes) ->
  'use strict'

  class MyApplication extends Chaplin.Application
    title: 'The title for your application'

    initialize: ->
      super
      @initRouter routes
define([
  'chaplin',
  'routes'
], function(Chaplin, routes) {
  'use strict';

  var MyApplication = Chaplin.Application.extend({
    title: 'The title for your application',

    initialize: function() {
      Chaplin.Application.prototype.initialize.apply(this, arguments);
      this.initRouter(routes);
    }
  });

  return MyApplication;
});