/phoenix-custom-event-hook

A LiveView hook for publishing and handling custom events

Primary LanguageJavaScriptMIT LicenseMIT

phoenix-custom-event-hook

This package is a Phoenix LiveView hook that allows you to easily send Custom Events to your live view.

Installation

In your phoenix project assets directory

npm install phoenix-custom-event-hook

Usage

  1. Add the PhoenixCustomEvent hook to your LiveSocket
import PhoenixCustomEvent from 'phoenix-custom-event-hook';

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, { params: { _csrf_token: csrfToken }, hooks: { PhoenixCustomEvent } })
  1. Add phx-hook and phx-custom-event- attributes to elements in your template.

In this example, the lit-google-element emits a bounds_changed custom event which will become live_view event.

<lit-google-map api-key="" phx-hook="PhoenixCustomEvent" phx-custom-event-bounds_changed="bounds_changed">
  1. Handle the event in your live view
  def handle_event(
        "bounds_changed",
        %{"north" => north, "east" => east, "west" => west, "south" => south},
        socket
      ) do
    airports =
      Airports.list_airports_in_bounds(%{north: north, east: east, west: west, south: south})

    {:noreply, socket |> assign(airports: airports)}
  end

An event target can be specified by assigning a component id to your custom element's phx-target attribute. In this example, any events emitted by the lit-google-map element will be handled by the LiveComponent that renders it, rather than the LiveView.

<lit-google-map api-key="" phx-hook="PhoenixCustomEvent" phx-target="<%= @myself %>" phx-custom-event-bounds_changed="bounds_changed">

Not currently supported: multiple event targets, targeting events by CSS selector.

Loading events

This hook will also dispatch the following events on the element it is added to:

  • phx-event-start when an event is sent to live view
  • phx-event-complete when a reply is received

Receiving events

If you wish to receive events from LiveView, add a phx-receive-events attribute to the element this hook is defined on which contains a list of events you wish to receive. Each event will become a CustomEvent of the same name with the detail property containing the payload.

For example, in LiveView:

  socket
  |> push_event("message_updated", %{message: "HI there"})

In your Custom Element:

  this.addEventListener("message_updated", ({ detail: { message } }) => {
    console.log(message);
  });

License

MIT.