Reload events after pushState.

This commit is contained in:
Mike Cao 2020-07-19 13:08:13 -07:00
parent 9cb08956c0
commit ed22d33d97
2 changed files with 26 additions and 10 deletions

File diff suppressed because one or more lines are too long

View File

@ -23,6 +23,7 @@ if (script) {
const screen = `${width}x${height}`; const screen = `${width}x${height}`;
let currentUrl = `${pathname}${search}`; let currentUrl = `${pathname}${search}`;
let currenrRef = document.referrer; let currenrRef = document.referrer;
const listeners = [];
/* Helper methods */ /* Helper methods */
@ -82,9 +83,11 @@ if (script) {
/* Handle push state */ /* Handle push state */
const handlePush = (state, title, url) => { const handlePush = (state, title, url) => {
removeEvents();
currenrRef = currentUrl; currenrRef = currentUrl;
currentUrl = url; currentUrl = url;
execute(currentUrl, currenrRef); execute(currentUrl, currenrRef);
setTimeout(loadEvents, 300);
}; };
const hook = (type, cb) => { const hook = (type, cb) => {
@ -101,19 +104,32 @@ if (script) {
/* Handle events */ /* Handle events */
document.querySelectorAll("[class*='umami--']").forEach(e => { const removeEvents = () => {
e.className.split(' ').forEach(c => { listeners.forEach(([element, type, listener]) => {
if (/^umami--/.test(c)) { console.log('removed', element.tagName, type);
const [, event, value] = c.split('--'); element.removeEventListener(type, listener, true);
if (event && value) { });
e.addEventListener(event, () => trackEvent(currentUrl, event, value), true); listeners.length = 0;
};
const loadEvents = () => {
document.querySelectorAll("[class*='umami--']").forEach(element => {
element.className.split(' ').forEach(className => {
if (/^umami--/.test(className)) {
const [, type, value] = className.split('--');
if (type && value) {
const listener = () => trackEvent(currentUrl, type, value);
listeners.push([element, type, listener]);
element.addEventListener(type, listener, true);
} }
} }
}); });
}); });
};
/* Start */ /* Start */
execute(currentUrl, currenrRef); execute(currentUrl, currenrRef);
loadEvents();
} }
} }