Home Manual Reference Source Repository
import Router from 'backbone/src/Router.js'
public class | source

Router

Extends:

Events → Router

Direct Subclass:

AppRouter

Backbone.Router - Provides methods for routing client-side pages, and connecting them to actions and events.

(http://backbonejs.org/#Router)

Web applications often provide linkable, bookmarkable, shareable URLs for important locations in the app. Until recently, hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API, it's now possible to use standard URLs (/page). Backbone.Router provides methods for routing client-side pages, and connecting them to actions and events. For browsers which don't yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL.

During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start() or Backbone.history.start({pushState: true}) to route the initial URL.

routes - router.routes The routes hash maps URLs with parameters to functions on your router (or just direct function definitions, if you prefer), similar to the View's events hash. Routes can contain parameter parts, :param, which match a single URL component between slashes; and splat parts *splat, which can match any number of URL components. Part of a route can be made optional by surrounding it in parentheses (/:optional).

For example, a route of "search/:query/p:page" will match a fragment of #search/obama/p2, passing "obama" and "2" to the action.

A route of "file/*path" will match #file/nested/folder/file.txt, passing "nested/folder/file.txt" to the action.

A route of "docs/:section(/:subsection)" will match #docs/faq and #docs/faq/installing, passing "faq" to the action in the first case, and passing "faq" and "installing" to the action in the second.

Trailing slashes are treated as part of the URL, and (correctly) treated as a unique route when accessed. docs and docs/ will fire different callbacks. If you can't avoid generating both types of URLs, you can define a "docs(/)" matcher to capture both cases.

When the visitor presses the back button, or enters a URL, and a particular route is matched, the name of the action will be fired as an event, so that other objects can listen to the router, and be notified. In the following example, visiting #help/uploading will fire a route:help event from the router.

Example:

routes: {
   "help/:page":         "help",
   "download/*path":     "download",
   "folder/:name":       "openFolder",
   "folder/:name-:mode": "openFolder"
}

router.on("route:help", function(page) {
   ...
});
Old extend - Backbone.Router.extend(properties, [classProperties])
Get started by creating a custom router class. Define actions that are triggered when certain URL fragments are
matched, and provide a routes hash that pairs routes to actions. Note that you'll want to avoid using a leading
slash in your route definitions:

var Workspace = Backbone.Router.extend({
   routes: {
      "help":                 "help",    // #help
      "search/:query":        "search",  // #search/kiwis
      "search/:query/p:page": "search"   // #search/kiwis/p7
   },

   help: function() {
      ...
   },

   search: function(query, page) {
      ...
   }
});
Converting the above example to ES6 using a getter method for `routes`:
class Workspace extends Backbone.Router {
   get routes() {
      return {
         "help":                 "help",    // #help
         "search/:query":        "search",  // #search/kiwis
         "search/:query/p:page": "search"   // #search/kiwis/p7
      };
   }

   help() {
      ...
   },

   search(query, page) {
      ...
   }
}
Basic default "no route router":
new Backbone.Router({ routes: { '*actions': 'defaultRoute' } });

Constructor Summary

Public Constructor
public

constructor(options: object)

When creating a new router, you may pass its routes hash directly as an option, if you choose.

Member Summary

Public Members
public

Stores the routes hash.

Method Summary

Public Methods
public

execute(callback: function, args: *[], name: string)

Execute a route handler with the provided parameters.

public abstract

Initialize is an empty function by default.

public

navigate(fragment: string, options: object): Router

Simple proxy to Backbone.history to save a fragment into the history.

public

route(route: string | RegExp, name: string, callback: function): Router

Manually bind a single named route to a callback.

Inherited Summary

From class Events
public

bind(): *

Delegates to on.

public

listenTo(obj: object, name: string, callback: function): Events

Tell an object to listen to a particular event on an other object.

public

listenToOnce(obj: object, name: string, callback: function): Events

Just like listenTo, but causes the bound callback to fire only once before being removed.

public

off(name: string, callback: function, context: object): Events

Remove a previously-bound callback function from an object.

public

on(name: string, callback: function, context: object): *

Bind a callback function to an object.

public

once(name: string, callback: function, context: object): *

Just like on, but causes the bound callback to fire only once before being removed.

public

stopListening(obj: object, name: string, callback: function): Events

Tell an object to stop listening to events.

public

Trigger callbacks for the given event, or space-delimited list of events.

public

unbind(): *

Delegates to off.

Public Constructors

public constructor(options: object) source

When creating a new router, you may pass its routes hash directly as an option, if you choose. All options will also be passed to your initialize function, if defined.

Override:

Events#constructor

Params:

NameTypeAttributeDescription
options object

Optional parameters which may contain a "routes" object literal.

See:

Public Members

public routes: object source

Stores the routes hash.

Public Methods

public execute(callback: function, args: *[], name: string) source

Execute a route handler with the provided parameters. This is an excellent place to do pre-route setup or post-route cleanup.

Params:

NameTypeAttributeDescription
callback function

Callback function to execute.

args *[]

Arguments to apply to callback.

name string

Named route.

See:

public abstract initialize() source

Initialize is an empty function by default. Override it with your own initialization logic.

See:

public navigate(fragment: string, options: object): Router source

Simple proxy to Backbone.history to save a fragment into the history.

Params:

NameTypeAttributeDescription
fragment string

String representing an URL fragment.

options object

Optional hash containing parameters for navigate.

Return:

Router

See:

public route(route: string | RegExp, name: string, callback: function): Router source

Manually bind a single named route to a callback. For example:

Params:

NameTypeAttributeDescription
route string | RegExp

A route string or regex.

name string

A name for the route.

callback function

A function to invoke when the route is matched.

Return:

Router

Example:

this.route('search/:query/p:num', 'search', function(query, num)
{
   ...
});

See: