vanillajs-deck/js/router.js

56 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 {
constructor() {
2019-11-24 00:02:31 +00:00
/**
* @property {HTMLDivElement} _eventSource Arbitrary DIV used to generate events
*/
2019-11-23 00:37:45 +00:00
this._eventSource = document.createElement("div");
2019-11-24 00:02:31 +00:00
/**
* @property {CustomEvent} _routeChanged Custom event raised when the route changes
*/
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
/**
* @property {string} _route The current route
*/
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, "/");
}
}