Skip to content
Snippets Groups Projects
Commit 8b88f82b authored by Daniel Kurowski's avatar Daniel Kurowski
Browse files

pass context to getter, not to VO constructor

parent a5114f45
No related branches found
No related tags found
1 merge request!12Improve work with value object
......@@ -5,22 +5,15 @@ export class HashTarget
{
private constructor(
private readonly value: string,
private readonly targetElement: HTMLElement,
) {}
public static fromString(value: string, document: HTMLDocument): HashTarget
public static fromString(value: string): HashTarget
{
if (value === '' || value === '#') {
throw new Error('Hash does not contain any fragment.');
}
const targetElementId = value.substring(1);
const targetElement = document.getElementById(targetElementId);
if (targetElement === null) {
throw new Error(`No referenced element with ID ${targetElementId} exists.`);
}
return new this(value, targetElement);
return new this(value);
}
public getHash(): string
......@@ -28,8 +21,14 @@ export class HashTarget
return this.value;
}
public getElement(): HTMLElement
public getRefElement(document: HTMLDocument): HTMLElement
{
return this.targetElement;
const targetElementId = this.value.substring(1);
const targetElement = document.getElementById(targetElementId);
if (targetElement === null) {
throw new Error(`No referenced element with ID ${targetElementId} exists.`);
}
return targetElement;
}
}
......@@ -15,6 +15,6 @@ export function initializeOnLinkClickScroll(): void
}
event.preventDefault();
scrollToTarget(HashTarget.fromString(element.hash, document));
scrollToTarget(HashTarget.fromString(element.hash));
})));
}
......@@ -22,7 +22,7 @@ export function initializeOnLoadScroll(): void
document.addEventListener('DOMContentLoaded', () => {
try {
hashTarget = HashTarget.fromString(hash, document);
hashTarget = HashTarget.fromString(hash);
} catch (e) {} // when URL contains hash which has no corresponding DOM element, just ignore it
});
......
......@@ -5,11 +5,11 @@ import {assert} from '../assert';
export function scrollToTarget(hashTarget: HashTarget|string, onScrollFinishedCallback?: () => void): void
{
if (typeof hashTarget === 'string') {
hashTarget = HashTarget.fromString(hashTarget, document);
hashTarget = HashTarget.fromString(hashTarget);
}
scrollToElement(
hashTarget.getElement(),
hashTarget.getRefElement(document),
() => {
assert(hashTarget instanceof HashTarget);
window.location.hash = hashTarget.getHash();
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment