Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 7x 7x 7x 1x 3x 3x 3x 3x 1x 4x 3x 4x | export class Router {
#global;
/** @type {Set<RouteCallback>} */
#routerSubscriptions = new Set();
/** @param {Pick<globalThis, 'addEventListener'> & { location: { hash: string }}} win */
constructor(win = window) {
this.#global = win;
this.#global.addEventListener('hashchange', () => {
this.#routerSubscriptions.forEach((sub) => sub(this.#currentRoute));
});
}
/** @param {string[]} route */
navigate(route) {
this.#currentRoute = route;
}
/** @param {RouteCallback} callback */
onNext(callback) {
this.#routerSubscriptions.add(callback);
callback(this.#currentRoute);
return () => {
this.#routerSubscriptions.delete(callback);
};
}
get #currentRoute() {
return this.#global.location.hash.substring(1).split('/');
}
set #currentRoute(route) {
this.#global.location.hash = `#${route.join('/')}`;
}
}
export const router = new Router();
|