Refactor sharing using feature pattern
This commit is contained in:
parent
8f23088244
commit
a246083b15
|
@ -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);
|
|
@ -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');
|
||||
});
|
||||
}
|
|
@ -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
|
||||
})
|
||||
}
|
||||
}
|
|
@ -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
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
});
|
||||
}
|
Loading…
Reference in New Issue