Module: LiveCable::Component::Events

Extended by:
ActiveSupport::Concern
Included in:
LiveCable::Component
Defined in:
lib/live_cable/component/events.rb

Instance Method Summary collapse

Instance Method Details

#dispatch_event(name, positional_detail = nil, window: false, **detail) ⇒ Object

Queue a DOM event to be dispatched on the client. Events are delivered with the next broadcast for this component - attached to the render when state changed, or on their own when it didn't - and fire on the client after the DOM has been morphed, so handlers see the updated markup.

On the client the event is a bubbling CustomEvent dispatched from the component's root element (or from window with window: true), so it can be handled with plain Stimulus data-action syntax:

Parameters:

  • name (String, Symbol)

    The event name (e.g. 'chat:message-sent')

  • detail (Hash)

    JSON-serializable payload, available as event.detail. Can be passed positionally or as bare keyword arguments; use the positional form if the payload itself needs a :window key.

  • window (Boolean) (defaults to: false)

    Dispatch on window instead of the component root



25
26
27
28
29
# File 'lib/live_cable/component/events.rb', line 25

def dispatch_event(name, positional_detail = nil, window: false, **detail)
  detail = positional_detail if positional_detail

  pending_events << { name: name.to_s, detail: detail.as_json, window: }
end

#flush_eventsArray<Hash>

Drain the queued events. Called when a broadcast is sent so each event is delivered exactly once.

Returns:

  • (Array<Hash>)


35
36
37
38
39
# File 'lib/live_cable/component/events.rb', line 35

def flush_events
  events = pending_events.dup
  pending_events.clear
  events
end