vanillajs-deck/js/router.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-11-24 00:02:31 +00:00
// @ts-check
/**
* Handles routing for the app
*/
2019-11-23 00:37:45 +00:00
export class Router {
2019-11-25 19:34:32 +00:00
/**
* Create a new Router instance
*/
2019-11-23 00:37:45 +00:00
constructor() {
2019-11-25 19:34:32 +00:00
/**
* Arbitrary element to source events
* @type {HTMLDivElement}
2019-11-24 00:02:31 +00:00
*/
2019-11-23 00:37:45 +00:00
this._eventSource = document.createElement("div");
2019-11-24 00:02:31 +00:00
/**
2019-11-25 19:34:32 +00:00
* Custom event raised when the route changes
* @type {CustomEvent}
2019-11-24 00:02:31 +00:00
*/
2019-11-23 00:37:45 +00:00
this._routeChanged = new CustomEvent("routechanged", {
bubbles: true,
cancelable: false
});
2019-11-24 00:02:31 +00:00
/**
2019-11-25 19:34:32 +00:00
* The current route
* @type {string}
2019-11-24 00:02:31 +00:00
*/
2019-11-23 00:37:45 +00:00
this._route = null;
window.addEventListener("popstate", () => {
if (this.getRoute() !== this._route) {
this._route = this.getRoute();
this._eventSource.dispatchEvent(this._routeChanged);
}
});
}
2019-11-24 00:02:31 +00:00
/**
* Get the event source
* @returns {HTMLDivElement} The event source div
*/
2019-11-23 00:37:45 +00:00
get eventSource() {
return this._eventSource;
}
2019-11-24 00:02:31 +00:00
/**
* Set the current route
* @param {string} route The route name
*/
2019-11-23 00:37:45 +00:00
setRoute(route) {
window.location.hash = route;
this._route = route;
}
2019-11-24 00:02:31 +00:00
/**
* Get the current route
* @returns {string} The current route name
*/
2019-11-23 00:37:45 +00:00
getRoute() {
return window.location.hash.substr(1).replace(/\//ig, "/");
}
}