Refactor sharing using feature pattern

This commit is contained in:
Karina Kwiatek 2021-08-10 13:16:40 +02:00
parent 8f23088244
commit a246083b15
5 changed files with 52 additions and 20 deletions

View File

@ -1,3 +1,7 @@
import start from '../retrospring/common';
import initAnswerbox from '../retrospring/features/answerbox/index';
start();
document.addEventListener('turbolinks:load', initAnswerbox);
document.addEventListener('turbolinks:load', initAnswerbox);
document.addEventListener('turbolinks:load', initAnswerbox);

View File

@ -0,0 +1,20 @@
import registerEvents from "retrospring/utilities/registerEvents";
import {createShareEvent} from "./share";
export default (): void => {
if (!('share' in navigator)) {
return;
}
document.body.classList.add('cap-web-share');
const entries: NodeList = document.querySelectorAll('.answerbox:not(.js-initialized)');
entries.forEach((element: HTMLElement) => {
console.log(element)
registerEvents([
{ type: 'click', target: element.querySelector('[data-action=ab-share]'), handler: createShareEvent(element) }
]);
element.classList.add('js-initialized');
});
}

View File

@ -0,0 +1,11 @@
export function createShareEvent(answerbox: HTMLElement): () => void {
return function (): void {
navigator.share({
url: answerbox.querySelector<HTMLAnchorElement>('.answerbox__answer-date > a').href
}).then(() => {
// do nothing, prevents exce ption from being thrown
}).catch(() => {
// do nothing, prevents exception from being thrown
})
}
}

View File

@ -1,20 +0,0 @@
import $ from 'jquery';
export default (): void => {
document.addEventListener('turbolinks:load', function () {
if (navigator.share) {
document.body.classList.add('cap-web-share')
$(document).on('click', 'button[name=ab-share]', function () {
const card = $(this).closest('.card')
navigator.share({
url: card.find('.answerbox__answer-date a')[0].href
}).then(() => {
// do nothing, prevents exception from being thrown
}).catch(() => {
// do nothing, prevents exception from being thrown
})
})
}
})
}

View File

@ -0,0 +1,17 @@
interface EventDef {
type: string;
target: Node | NodeList;
handler: EventListenerOrEventListenerObject;
}
export default function registerEvents(events: EventDef[]): void {
events.forEach(event => {
if (event.target instanceof NodeList) {
event.target.forEach(element => {
element.addEventListener(event.type, event.handler);
});
} else if (event.target instanceof Node) {
event.target.addEventListener(event.type, event.handler);
}
});
}