UNPKG

pragma-views2

Version:

77 lines (63 loc) 2.21 kB
import { BaseElement } from "../../lib/base-element.js"; class RouteListener extends BaseElement { async connectedCallback() { super.connectedCallback(); const routePath = this.getAttribute("src"); const result = await fetch(routePath).then(result => result.text()); this.routes = JSON.parse(result); this.registerEvent(window, "hashchange", this.urlChanged.bind(this)); if (document.readyState == "complete") { this.urlChanged(); } else { this._updateWhenReady(); } } disconnectedCallback() { this.routes = null; super.disconnectedCallback(); } _updateWhenReady() { document.onreadystatechange = state => { if (document.readyState == "complete") { this.urlChanged(); } }; } urlChanged() { this.loadView(this.getUrlParts()); } getUrlParts() { const locationHash = window.location.hash.split("#")[1]; if (locationHash == undefined) { return { hash: "" }; } const paramIndex = locationHash.indexOf("?"); if (paramIndex == -1) { return { hash: locationHash }; } const hashValue = locationHash.slice(0, paramIndex); const params = locationHash.slice(paramIndex + 1).split("&").reduce(function (result, item) { const parts = item.split('='); result[parts[0]] = parts[1]; return result; }, {}); return { hash: hashValue, parameters: params }; } loadView(args) { const route = this.routes[args.hash]; const view = route == undefined ? "404" : route.view; const containerId = this.getAttribute("view-container"); const container = document.querySelector(`#${containerId}`); container.showView(view, () => { container.viewModel.parameters = args.parameters; }); } } customElements.define("route-listener", RouteListener);