Livex.Utils (livex v0.2.0)

Utility functions for Livex components and views.

This module provides helper functions for event handling, JavaScript execution, and state management with dependency tracking.

Summary

Functions

Assigns a new value to the socket if it doesn't exist or if any of its dependencies have changed.

Emits a client-side event from the server.

Pushes a JavaScript command to be executed on the client.

Functions

assign_new(socket, key, deps, fun)

Assigns a new value to the socket if it doesn't exist or if any of its dependencies have changed.

This function is similar to Phoenix.Component.assign_new/3, but with dependency tracking. It will recompute the value if any of the dependencies have changed in the socket's assigns.

Parameters

  • socket - The LiveView socket
  • key - The key to assign the value to
  • deps - A list of keys that this value depends on
  • fun - A function that returns the value to assign

Examples

def pre_render(socket) do
  {:noreply,
   assign_new(socket, :location, [:location_id], fn assigns -> 
     MyApp.Domain.get_location!(assigns.location_id)
   end)}
end

push_emit(socket, event, opts \\ [])

Emits a client-side event from the server.

This function allows components to emit events that can be handled by parent components or views, similar to how JSX.emit works but from server-side code.

Parameters

  • socket - The LiveView socket
  • event - The event suffix (will be looked up in assigns as "phx-#{event}")
  • opts - Options to pass to the event (default: [])

Examples

def handle_event("close", _, socket) do
  {:noreply, socket |> push_emit(:close)}
end

push_js(socket, js)

Pushes a JavaScript command to be executed on the client.

Parameters

  • socket - The LiveView socket
  • js - The Phoenix.LiveView.JS struct containing operations to execute

Returns

  • The updated socket

send_message(module, socket, event, payload)

stream_new(socket, key, deps, fun)