IT:AD:Durandal.JS:HowTo:Navigation
Process
Routing Basics
Durandal/'s navigation is provided via a plugin (app/durandal/plugins/router.js) that by default is using the Sammy.JS/
library.
The router module is loaded early, either in main.js, or shell.js (I prefer shell.js for more fine grain control):
define(['durandal/plugins/router', 'durandal/app', 'durandal/system', 'data/settings'],
function (router, app, system, settings) {
....
}
Where routes can be added/registered, as follows:
var routes = [
{ url: 'welcome', moduleId: 'viewmodels/welcome', name: 'Welcome', visible: false, settings: {} },
{ url: 'students', moduleId: 'viewmodels/students', name: 'Students', visible: true, settings: {} },
...
{ url: 'students', moduleId: 'viewmodels/students/add', name: 'Students', visible: true, settings: {} },
];
router.map(settings.routes);
Note:
- routes can be registered one at a time, or as an array (but array is probably the common scenario).
- there is no built in method unregister a route (but that is not going to be a common scenario at all).
- Looking at Popping open
app/durandal/plugins/router.js@configureRoute(routeInfo)one can see that each route added is going to be added to therouter.allRoutesko.observableArray.- Of those, the ones marked
visible : true(the default value), will also be added torouter.visibleRoutesko.observableArray
Popping open app/durandal/plugins/router.js one sees that the following ko.observables:
allRoutes = ko.observableArray([]),
visibleRoutes = ko.observableArray([]),
ready = ko.observable(false),
isNavigating = ko.observable(false),
...
activeItem = viewModel.activator(),
activeRoute = ko.observable(),
That's going to be very useful for making dynamic menus:
As for the more prosaic navigation around pages, you have a couple of solutions.
The first, is simply putting links in your page, that match the routes you registered earlier:
<a href="#/students/add">Add...</a>
matching the following route:
{ url: 'students', moduleId: 'viewmodels/students/add', name: 'Students', visible: true, settings: {} },
That's easy enough… can go forward, and can go back as long as you are returning to the same location.
Making a Back Button
Demos will show putting a link behind a Form Cancel link. That will work if the Cancel button will always go back to the same location.
But if the View (eg: a Details View) can be called from two locations, the Click has to be bound using IT:AD:Knockout.JS to a method on the View
that in turn calls
router.navigateBack();