The URL Router
The purpose of routes is to give the user a URL in the browser’s location bar.
Routes mapped in an application using events look like this:
export var routes = [
[ '/auth/loginSuccess', 'auth.loginSuccess' ],
['/u/:username/profile', 'profile.show'],
[ '/', 'main.home' ]
];
Routes mapped in an application using functions without events look like this:
export var routes = [
['/auth/loginSuccess', loginSuccess],
['/u/:username/profile', showUserProfile],
['/', home]
];
Using router.open()
// Define a handler function for the /u/:username/profile route
function showUserProfile(params) {
console.log('Showing user profile for:', params.username);
}
// Navigate to the /u/johndoe/profile route
a7Router.open('/u/johndoe/profile', { username: 'johndoe' });
In this example, we first define a handler function for the /u/:username/profile
route. Then, we add this route and parameters to router.open()
, which updates the browser’s URL and calls the appropriate handler.
Using router.match()
The router.match()
method allows you to handle route changes dynamically without updating the browser’s URL. This is useful for handling hashchange events or external navigation:
// Function to handle route changes
function handleRouteChange() {
let path = window.location.pathname + window.location.search;
a7Router.match(path);
}
// Bind the handleRouteChange function to hashchange events
window.addEventListener('hashchange', handleRouteChange);
// Simulate navigation to /u/johndoe/profile using hashchange event
window.location.hash = '/u/johndoe/profile';
In this example, we first define a handler function for the /u/:username/profile
route and add it. Then, we create a handleRouteChange()
function that uses router.match()
to handle changes in the URL path.
By using these methods, you can dynamically navigate within your application and handle route changes programmatically or through external events.
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.