Simple router in JavaScript. Works with URL in hash format, and without params.
Start a new instance of the class:
const router = new Router('#app')
The constructor admits two parameters. The first one is the DOM element where the routes will be rendered (mandatory), and the second one is an optional callback function. This function must return the HTML we want to render.
const router = new Router('#app', function() {
return "The current route doesn't exists";
})
For adding new routes use the addRoute method. It needs the route starting with / as first parameter, and a callback function returning the HTML to render as the second one.
router.addRoute('/about', function() {
return "Welcome to the <strong>about</strong> page";
})
For the router to work, it's necessary to run the next script:
router.start();
Be sure to add it after the definition of the routes. Without it, the router will be able to detect the hash changes and show the new URL, but it won't load the initial URL the web is open from.
Add a # symbol before your routes in your HTML links.
<a href="#/about">About</a>
Use Babel to transpile your code and make sure that it works with every browser.
These features are planned to be added in the future.
- Parameters in the URL compatibility.
- Singleton pattern.
- Complex routes handling.