Routing
altseven includes a Trie-based client-side URL router for bookmarking and browser history. Routes map URL patterns to events (or handler functions).
Declaring routes
Routes are declared in the router option as [ path, handler ] pairs:
export const myApp = new Application( {
remote: {},
router: {
useEvents: true, // default: handlers are event topics
routes: [
[ "/", "app.home" ],
[ "/notes", "notes.list" ],
[ "/notes/:noteID", "notes.detail" ],
[ "/settings/profile", "settings.profile" ]
]
}
} );
With useEvents: true (the default), the handler string is a topic published
on myApp.events when the route matches. With useEvents: false, handlers are
called as functions: [ "/", ( params ) => { ... } ].
Paths support :param segments — /notes/:noteID matches /notes/n42 and
extracts { noteID: "n42" }.
Navigating
// simple navigation — publishes "app.home"
myApp.router.open( "/" );
// with parameters — merged with any route-pattern parameters
myApp.router.open( "/notes/n42", { highlight: true } );
open() pushes a history entry (parameters become the history state) and then
dispatches, so the back button works. If no route matches, the router logs an
error and does nothing.
Matching the current URL
Routes do not fire on page load
The router handles back/forward via window.onpopstate, but it does not
match the URL the page was loaded with. After your views are created, route the
initial URL yourself:
await myApp.init();
// ... create views ...
myApp.router.match( document.location.pathname + document.location.search );
match() behaves like open() but is intended for the initial navigation.
Without it, a fresh visit or reload of /notes/n42 renders an empty shell.
Route handlers as event subscribers
Following the pub/sub conventions, subscribe to your route topics inside your startup function:
myApp.events.subscribe( "notes.detail", ( params ) => {
// params = { noteID: "n42", ...anything passed to open() }
detailView.setState( { noteID: params.noteID } );
} );
Routes exist to give the user a URL in the browser’s location bar; the actual logic lives in the event handlers, which keeps routes, views and events decoupled.
Nested paths
Since 8.3.0 the router handles nested paths (base-case matching), so
/settings/profile and /settings can coexist without shadowing each other.
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.