Components

This document explains Azu's live component system, which enables real-time, stateful UI updates without writing JavaScript.

What are Components?

Components are server-side objects that:

  • Maintain state on the server

  • Render HTML

  • Respond to user events

  • Push updates to the browser

class CounterComponent
  include Azu::Component

  @count = 0

  def content
    <<-HTML
    <div>
      <span>Count: #{@count}</span>
      <button azu-click="increment">+</button>
    </div>
    HTML
  end

  on_event "increment" do
    @count += 1
    push_state
  end
end

How Components Work

Architecture

Event Flow

  1. User clicks button in browser

  2. Spark JS sends event via WebSocket

  3. Server component receives event

  4. Component updates state

  5. Component re-renders HTML

  6. Server sends HTML diff to browser

  7. Spark JS patches the DOM

Component Lifecycle

Lifecycle Stages

State Management

Component State

State lives in instance variables:

Updating State

Update state and push to client:

Event Handling

Event Attributes

Connect HTML to component events:

Event Data

Send data with events:

Two-Way Binding

Bind form inputs:

The @name variable updates when the input changes.

Optimized Updates

Full Re-render

push_state re-renders the entire component:

Partial Updates

For performance, update only parts:

Props and Initialization

Component Properties

Pass initial data to components:

HTML Mounting

Real-Time Updates

Server-Initiated Updates

Components can receive updates from server events:

Periodic Updates

Update on intervals:

Component Communication

Parent-Child

Nest components and pass events up:

Global Events

Use a message bus:

When to Use Components

Good Use Cases

  • Interactive forms

  • Real-time dashboards

  • Live search/filtering

  • Chat interfaces

  • Notifications

  • Dynamic lists

When to Use Plain Endpoints

  • Static content

  • Simple forms with redirects

  • API responses

  • File downloads

See Also

Last updated

Was this helpful?