UNPKG

yourrouter

Version:

A powerful router based on client-side routing.

47 lines (46 loc) 2.29 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { Redirect } from '../../router/domain/redirect'; import { GetRouteInfo } from '../../routes/application/GetRouteInfo'; import { RenderRoute } from '../../rendering/application/RenderRoute'; import { ExecuteCurrentRouteCallback } from './ExecuteCurrentRouteCallaback'; export class MountRouter { constructor(config) { this.redirect = new Redirect(); this.getRouteInfo = new GetRouteInfo(); this.executeCurrentCallback = new ExecuteCurrentRouteCallback(); this.path404 = config.path404; this.renderId = config.renderId; this.renderRoute = new RenderRoute(this.renderId); } mount() { return __awaiter(this, void 0, void 0, function* () { window.location.hash = '/'; window.addEventListener('hashchange', (e) => __awaiter(this, void 0, void 0, function* () { return yield this.onHashChange(e); })); }); } onHashChange(event) { return __awaiter(this, void 0, void 0, function* () { event.preventDefault(); const currentUserPath = this.getRouteInfo.path(); const theCurrentPathExist = this.getRouteInfo.isValidRoute(currentUserPath); if (!theCurrentPathExist) { this.redirect.to(this.path404); return; } const templateRenderingIsDisable = this.renderId === undefined; if (templateRenderingIsDisable) { yield this.executeCurrentCallback.execute(); return; } yield this.renderRoute.renderCurrentRoute(); }); } }