vanillajs-deck/js/router.js

30 lines
771 B
JavaScript
Raw Normal View History

2019-11-23 00:37:45 +00:00
export class Router {
constructor() {
this._eventSource = document.createElement("div");
this._routeChanged = new CustomEvent("routechanged", {
bubbles: true,
cancelable: false
});
this._route = null;
window.addEventListener("popstate", () => {
if (this.getRoute() !== this._route) {
this._route = this.getRoute();
this._eventSource.dispatchEvent(this._routeChanged);
}
});
}
get eventSource() {
return this._eventSource;
}
setRoute(route) {
window.location.hash = route;
this._route = route;
}
getRoute() {
return window.location.hash.substr(1).replace(/\//ig, "/");
}
}