From de0efe96a3e7f8e6fd6bdae1018817f0ee4a66b9 Mon Sep 17 00:00:00 2001 From: Carles Mitjans Date: Mon, 9 Dec 2024 13:24:40 +0100 Subject: [PATCH 1/2] fix: avoid duplicating events --- src/runtime/directives/v-posthog-capture.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/runtime/directives/v-posthog-capture.ts b/src/runtime/directives/v-posthog-capture.ts index 791a10d..f77f740 100644 --- a/src/runtime/directives/v-posthog-capture.ts +++ b/src/runtime/directives/v-posthog-capture.ts @@ -4,12 +4,16 @@ import type { ObjectDirective, FunctionDirective } from 'vue'; const directive: FunctionDirective = (el, { value, arg }) => { const { $clientPosthog } = useNuxtApp(); - el.addEventListener(arg ?? 'click', () => { - if (!$clientPosthog) return; + if (!el.hasAttribute('posthog-listener')) { + el.setAttribute('posthog-listener', 'true'); - if (typeof value === 'string') $clientPosthog.capture(value); - else $clientPosthog.capture(value.name, value.properties); - }); + el.addEventListener(arg ?? 'click', () => { + if (!$clientPosthog) return; + + if (typeof value === 'string') $clientPosthog.capture(value); + else $clientPosthog.capture(value.name, value.properties); + }); + } }; export const vPostHogCapture: ObjectDirective = { From 5af68446b4cc4957772b0836788c2dd031e1b372 Mon Sep 17 00:00:00 2001 From: Carles Mitjans Date: Mon, 9 Dec 2024 13:26:35 +0100 Subject: [PATCH 2/2] refactor: avoid nested ifs --- src/runtime/directives/v-posthog-capture.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/runtime/directives/v-posthog-capture.ts b/src/runtime/directives/v-posthog-capture.ts index f77f740..e248f04 100644 --- a/src/runtime/directives/v-posthog-capture.ts +++ b/src/runtime/directives/v-posthog-capture.ts @@ -4,16 +4,16 @@ import type { ObjectDirective, FunctionDirective } from 'vue'; const directive: FunctionDirective = (el, { value, arg }) => { const { $clientPosthog } = useNuxtApp(); - if (!el.hasAttribute('posthog-listener')) { - el.setAttribute('posthog-listener', 'true'); + if (el.hasAttribute('posthog-listener')) return; - el.addEventListener(arg ?? 'click', () => { - if (!$clientPosthog) return; + el.setAttribute('posthog-listener', 'true'); - if (typeof value === 'string') $clientPosthog.capture(value); - else $clientPosthog.capture(value.name, value.properties); - }); - } + el.addEventListener(arg ?? 'click', () => { + if (!$clientPosthog) return; + + if (typeof value === 'string') $clientPosthog.capture(value); + else $clientPosthog.capture(value.name, value.properties); + }); }; export const vPostHogCapture: ObjectDirective = {