Listeners plugin

To be able to react to route changes, you might need to add listeners. listenersPlugin plugin provides different ways to listen to router state changes.

import listenersPlugin from 'router5/plugins/listeners';

const router = createRouter()
    .usePlugin(listenersPlugin());

Three types of listeners

Navigation from 'users.view' to 'orders.completed'

When navigation from users.view to orders.completed:

Navigation from 'orders.completed' to 'orders.pending'

When navigation from orders.pending to orders.pending:

Listener Arguments

Listeners will be called with toState and fromState arguments. State objects contain the following properties: name, params and path.

Listen to a node change

addNodeListener(name, fn) will register a listener which will be invoked when the specified route node is the transition node of a route change, i.e. the intersection between deactivated and activated segments.

For example, when navigating from route name A.1.a to A.1.b, node a.1 is the apex node. When navigating from A.1.a to A.2, A is the apex.

Node listeners are limited to one listener per node, and are the most useful listener for component trees: they allow to use wrapping components and to re-render a view efficiently at a specific node. Using addNodeListener('', fn) will add a listener for the router's unamed root node.

If autoCleanUp option is set to true, node listeners are automatically removed when their associated node no longer exists.

myRouter.addNodeListener('A', function (toState, fromState) {
    console.log('re-render from A');
});

myRouter.addNodeListener('A.1', function (toState, fromState) {
    console.log('re-render from A.1');
});

myRouter.navigate('A.1.a');
myRouter.navigate('A.1.b'); // => logs 're-render from A.1'
myRouter.navigate('A.2');   // => logs 're-render from A'

Listen to any route change

Listeners registered with addListener(fn) will be triggered on any route change, including route reloads (toState will be equal to fromState). You can remove a previously added listener by using removeListener(fn).

function callback(toState, fromState) {
    renderComponent(toState.name);
}

myRouter.addListener(callback);

myRouter.removeListener(callback);

Listen to a specific route

addRouteListener(name, fn) will register a listener which will be triggered when the router is navigating to the supplied route name.

Listeners registered with addRouteListener(name, fn) can be removed later with removeRouteListener(name, fn)

var myRouter = Router5()
    .addNode('home', '/home')
    .addNode('about', '/about')
    .start();

myRouter.addRouteListener('home', function (toState, fromState) {
    alert('You have navigated to home');
});

myRouter.addRouteListener('about', function () {
    alert('You have navigated to about');
});

myRouter.navigate('home');  // => alerts 'You have navigated to home'
myRouter.navigate('about'); // => alerts 'You have navigated to about'