1.0.1 • Published 1 year ago
@jmdevcraft/hash-router v1.0.1
HashRouter
The HashRouter class is a simple hash router implementation for web applications.
Options
basename: The base path of the application. Defaults to an empty string.useparams: A boolean indicating whether the router should handle route parameters. Defaults tofalse.
Methods
constructor(opts)
Creates a new instance of the router with the provided options.
opts: An object with options for the router.
navigate(to)
Navigates to the specified route.
to: The route to navigate to.
path(pathname, cb)
Registers a new route and its corresponding callback.
pathname: The route to register.cb: The callback to execute when navigating to the route.
parseURL(path)
Converts a path into a full hash URL.
path: The path to convert.
init()
Initializes the router. Registers the hash change event and loads the current route.
Private Properties
#options: An object storing options for the router.#routes: An array storing registered routes and their callbacks.#pathname: Gets the current path from the URL hash.#query: Gets search parameters from the URL hash.#params: Gets parameters for the current route ifuseparamsis enabled.
Usage Example
import {HashRouter} from '@jmdevcraft/hash-router'
const router = new HashRouter({
basename: '/myapp',
useparams: true
});
router.path('/home', (req) => {
// handle the /home route
});
router.path('/profile/:id', (req) => {
// req.params.id
});s
router.path((req) => {
// page not found
});
router.init();