I have a JavaScript hook in my Phoenix LiveView layout that detects timezone changes and sends an “update_timezone” event via pushEvent
. Currently I’m copy-pasting the same handle_event("update_timezone", ...)
function across all my LiveViews.
What’s the best way to handle this event globally across all LiveViews without duplicating the handler code? The hook is in the layout template but layouts aren’t LiveViews themselves, so I can’t put the handler there.
# layouts.ex
<main class="min-h-screen">
<%= if @current_scope do %>
<div
id="timezone-detector"
phx-hook="TimezoneDetector"
data-authenticated="true"
data-current-timezone={@current_scope.user.timezone}
class="hidden"
>
</div>
<% end %>
...
My hook:
const TimezoneDetector = {
mounted() {
// Only update if user is authenticated
if (this.el.dataset.authenticated === "true") {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const currentTimezone = this.el.dataset.currentTimezone;
// Only send update if timezone is different
if (timezone && timezone !== currentTimezone) {
this.pushEvent("update_timezone", { timezone: timezone });
}
}
}
};
Where do I put the handle_event so it’s global?