JS Routing with Navigo
KVision supports JavaScript routing with optional modules since version 4.1.0. Two modules are available kvision-routing-navigo
, based on Navigo 7 library (for compatibility with earlier KVision versions) and kvision-routing-navigo-ng
, based on current Navigo 8+.
Add the following in your build.gradle.kts
file
Navigo 7: implementation("io.kvision:kvision-routing-navigo:$kvisionVersion")
Navigo 8+: implementation("io.kvision:kvision-routing-navigo-ng:$kvisionVersion")
The following examples are using kvision-routing-navigo-ng
module.
Initializing
Call the Routing.init()
method at the beginning of your Application.start()
method.
By default, the router uses hash-based routing and sets the strategy equal to "ONE". This means that when a match is found, the router stops resolving other routes. Optional parameters of init()
allow you to fully configure Navigo instance.
The init()
function returns the configured router object, which can be used to call all Navigo API methods.
Adding a route
To add a route, use the on
method of the router object, which can take different parameters.
In all of these approaches, you pass in a function that is invoked when the route is matched.
Resolve has to be called at least once. The method does the following
Searches for a url match
If yes, it calls hooks and your route handler
updates the router's internal state
(Note, if you set strategy = "ALL", it will keep searching)
Navigating
To navigate to a certain url, use the navigate
method on the router object.
To ensure that routing in link elements also works correctly with Navigo, augment the link()
element according to Navigo’s conventions. This will align your links with Navigo’s handling of navigation events. For more details, refer to the official documentation: Navigo Augmenting Links.
Hooks
Hooks are functions that are fired during the resolving process. There are four hooks that are fired:
before
after
leave
already
You can override hooks for all routes, e.g.
or specific routes
Usage with Panel
The JS router support is also directly available in the TabPanel
and StackPanel
containers. This way you can easily bind different parts of your application GUI with distinct URL addresses and make the "Back" button of the browser work as expected.
When using routing built into TabPanel
or StackPanel
components and also declaring manual routing with the same routes, remember to change the routing strategy from the default Strategy.ONE
to Strategy.ALL
.
Last updated