Wondering what’s next for npm?Check out our public roadmap! »

router5

0.0.1-alpha.10 • Public • Published

npm version Build Status Coverage Status

router5

This library is in alpha version. Although it is functional and fully tested, API is subject to change whithout notice.

An simple but powerful HTML5 router, based on route-node and path-parser.

What is it?

It is an HTML5 router, using history and organising named routes in a tree. Browser support is limited to modern browsers implementing session history: http://caniuse.com/#search=history.

Router 5 supports use of hash in URL, but session history is still required: deciding to use a hash or not is therefore not a decision based on browser support, but rather a decision based on server capabilities!

It is aimed at applications rendering a tree of components, but can easily be used elsewhere. This router is library and framework agnostic, and makes no asumption on your implementation. It favours covention over configuration, by giving you the means to observe route changes and to react to them. Afterall, why treat route changes any different than data changes?

Features

  • Use of hash (#)
  • Default start route: a default route to navigate to on load if the current URL doesn't match any route. Similar to $routeProvider.otherwise() in Angular ngRoute module.
  • Start and stop router
  • Nested named routes: routes are identified by names and parameters so you don't have to manipulate URLs directly. Routes can be nested, introducing the notion of route segments.
  • __Route change listeners: listen to any route change, or register listeners for a specific route.
  • Route node change listeners: you can add listeners to be triggered on a specific named route node. They will be triggered if that named route node is the node a component tree needs to be re-rendered from.
  • Segments deactivation: you can register segment components. On a route change, it will ask those components through their canDeactivate method if they allow navigation. Similar to Angular 2 and Aurelia routers.
  • You are in control! You decide what to do on a route change and how to do it.

API

Constructor

new Router5(routes, opts)

You can supply a list of routes or a RootNode object:

  • If you supply a list of routes (either RouteNode objects or POJOs), a root node will be added (unamed route and empty URL).
  • If you supply a single RootNode object, it will be used as a root node (handy if you want to prefix all your routes)

Using plain objects:

import Router5 from 'router5'
 
let router = new Router5([
    {name: 'users', path: '/users', [
        {name: 'view', path: '/view/:id'},
        {name: 'list', path: '/list'}
    ]},
    {name: 'orders', path: '/orders'}
])

Using RouteNode:

import Router5   from 'router5'
import RouteNode from 'route-node'
 
let userRoutes = new RouteNode('users', '/users', [
    new RouteNode('view', '/view/:id'),
    new RouteNode('list', '/list')
])
 
let ordersRoute = new RouteNode('orders', '/orders', [
    new RouteNode('view', '/view/:id'),
    new RouteNode('pending', '/pending'),
    new RouteNode('completed', '/completed')
])
 
let router = new Router5([
    userRoutes,
    ordersRoute,
    new RouteNode('home', '/home')
], {
    defaultRoute: 'home',
    useHash: true
})

The simplest way to create routes:

import Router5 from 'router5'
 
let router = new Router5()
    .addNode('users',      '/users')
    .addNode('users.view', '/view/:id')
    .addNode('users.list', '/list')

Options:

  • useHash: true|false, default to false
  • defaultRoute: the route name to navigate to when instanciating the router. It will only navigate to the default route if the current URL doesn't match an existing route.
  • defaultParams: the parameters to use with the default route name.

Router instance API

router.setOption(opt, value)

A chainable method to set a specific option.

router.start()

Start the router listening to popstate events and allow navigation. On start, the router will navigate to the default provided route if the current URL doesn't match any already defined route.

router.stop()

Stop the router listening to popstate events and prevent navigation.

router.add(route)

  • route Array[Object|RouteNode]|RouteNode|Object Add routes to the route tree

router.addNode(name, path)

  • name String the name of the route to add. You can add a nested route by specifying its full name (i.e. 'a.b.c.d').
  • path String the route path. For a full syntax overview, see path-parser.

router.rootNode

The top node RouteNode instance. For a detailled API, see RouteNode's README

router.buildPath(name, params)

Build path for a route name and params.

router.buildPath('users.view', {id: 1}) // => "/users/view/1"

router.getState()

Return the current state.

router.getState() // => {name: "home", params: {}, path: "/home"}

router.registerComponent(name, component)

Register a component for the named route segment name. name has to describe the full route name (i.e. 'users.view'). If the route segment for the registered component is about to be removed by a route change, its canDeactivate(toState, fromState) method will be called if present. Segments to be deactivated are called from bottom to top.

Only one component per segment can be registered.

router.registerComponent('users', usersComponent)
router.registerComponent('users.view', userViewComponent)

router.deregisterComponent(name)

It will remove the registered component for a specific route segment.

router.deRegisterComponent('users.view');

router.addListener(fn)

The provided callback will be executed on a route change with new and old state objects. State objects contain route name, route params and route path properties.

router.addListener(function (newState, oldState) {
    console.log(newState) // => {name: "users.view", "params": {id: 1}, "path": "/users/view/1"}
});

router.removeListener(fn)

Removes a listener.

router.addRouteListener(name, fn)

The provided callback will be executed when route `` is activated.

router.removeRouteListener(name, fn)

Removes a route listener.

router.addNodeListener(name, fn)

Similar to addListener(fn), except that it will be triggered only if the route segment name is the lowest surviving route segment on a route change.

  • When navigating from users.view to users.list, listeners on users and global listeners will be called.
  • When navigation from orders.list to users.view, only global listeners will be called.

router.addNodeListener('', fn) is equivalent to router.addListener(fn).

router.removeNodeListener(name, fn)

Remove a node listener.

router.navigate(name, params, opts)

Navigate to the specified route name and params. Available options:

  • reload true|false, default to false: if trying to navigate to the current route, nothing will happen unless reload is set to true
  • replace true|false, default to false: whether or not the current history entry should be replaced

Install

npm i [email protected]

Version

0.0.1-alpha.10

License

MIT

Last publish

Collaborators

  • avatar