|
| 1 | +/** |
| 2 | + * @internalapi |
| 3 | + * @module vanilla |
| 4 | + */ /** */ |
| 5 | + |
| 6 | +import { LocationServices } from "../common/coreservices"; |
| 7 | +import { Disposable } from "../interface"; |
| 8 | +import { UIRouter } from "../router"; |
| 9 | +import { LocationLike, HistoryLike } from "./interface"; |
| 10 | +import { parseUrl, getParams, buildUrl } from "./utils"; |
| 11 | +import { isDefined } from "../common/predicates"; |
| 12 | +import { extend, deregAll, removeFrom } from "../common/common"; |
| 13 | +/** A base `LocationServices` */ |
| 14 | +export abstract class BaseLocationServices implements LocationServices, Disposable { |
| 15 | + constructor(router: UIRouter, public fireAfterUpdate: boolean) { |
| 16 | + this._location = window && window.location; |
| 17 | + this._history = window && window.history; |
| 18 | + } |
| 19 | + |
| 20 | + _listener = evt => this._listeners.forEach(cb => cb(evt)); |
| 21 | + |
| 22 | + private _listeners: Function[] = []; |
| 23 | + _location: LocationLike; |
| 24 | + _history: HistoryLike; |
| 25 | + |
| 26 | + abstract _get(): string; |
| 27 | + abstract _set(state: any, title: string, url: string, replace: boolean); |
| 28 | + |
| 29 | + hash = () => parseUrl(this._get()).hash; |
| 30 | + path = () => parseUrl(this._get()).path; |
| 31 | + search = () => getParams(parseUrl(this._get()).search); |
| 32 | + |
| 33 | + url(url?: string, replace: boolean = true): string { |
| 34 | + if (isDefined(url) && url !== this._get()) { |
| 35 | + this._set(null, null, url, replace); |
| 36 | + |
| 37 | + if (this.fireAfterUpdate) { |
| 38 | + let evt = extend(new Event("locationchange"), { url }); |
| 39 | + this._listeners.forEach(cb => cb(evt)); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return buildUrl(this); |
| 44 | + } |
| 45 | + |
| 46 | + onChange(cb: EventListener) { |
| 47 | + this._listeners.push(cb); |
| 48 | + return () => removeFrom(this._listeners, cb); |
| 49 | + } |
| 50 | + |
| 51 | + dispose(router: UIRouter) { |
| 52 | + deregAll(this._listeners); |
| 53 | + } |
| 54 | +} |
0 commit comments