# Callbacks & Events

- **Section:** Core Concepts
- **URL:** https://refast.fastapicloud.dev/docs/concepts/callbacks
- **Markdown:** https://refast.fastapicloud.dev/docs/concepts/callbacks.md
- **Source:** https://github.com/idling-mind/refast-docs/blob/main/docs/pages/concepts/callbacks.py
- **Live examples:** the widgets on this page need a browser; open the URL above to try them.
- **Applies to:** refast 0.12.2

## Overview

Callbacks bridge browser events and Python over WebSocket. Each event sends the callback
ID, bound kwargs, optional prop values, and raw event data to the server before invoking
your function.

Different components support different event types (e.g. `on_click`, `on_change`, `on_keydown`),
but the callback pattern is consistent: create a callback with `ctx.callback()`, then pass
it to your component's event prop. Inside the callback, use `ctx` methods to update the UI,
show toasts, and more.

In addition to python callbacks (`ctx.callback`), you can run client-only JavaScript with
`ctx.js()` for instant interactivity without a server roundtrip, or combine both in one
event by calling chaining `ctx.js()` and `ctx.callback()` together using `ctx.chain()`,
or by invoking Python from JavaScript with `refast.invoke()`. You can also just store event
data in the browser without a server hop using `ctx.save_prop()`. We'll cover all these patterns
in this section.

## Basic usage

```python
async def handle_click(ctx: Context, item_id: str):
    await ctx.show_toast(f"Clicked {item_id}!", variant="success")

Button("Click Me", on_click=ctx.callback(handle_click, item_id="Item 1"))
```

## Callback with bound args

Attach static kwargs when you create the callback. Great for passing IDs, variants, or
mode flags without relying on client props.

```python
async def send_order(ctx: Context, flavor: str):
    await ctx.show_toast(f"Queued {flavor}")

Button("Vanilla", on_click=ctx.callback(send_order, flavor="vanilla")),
Button("Mocha", on_click=ctx.callback(send_order, flavor="mocha"), variant="secondary"),
Button("Chai", on_click=ctx.callback(send_order, flavor="chai"), variant="outline"),
```

## save_prop + props

`ctx.save_prop(name)` captures event data in the browser without a server hop. Use
`props=[...]` when creating a callback to forward those client-side values to Python.

```python
Input(placeholder="Your name", on_change=ctx.save_prop("demo_prop_name"))
Button("Submit with props", on_click=ctx.callback(submit, props=["demo_prop_name"]))

async def submit(ctx: Context, demo_prop_name: str = ""):
    await ctx.show_toast(f"Hello, {demo_prop_name}!")
```

## Client-only `ctx.js` (Press Enter)

Run JavaScript directly in the browser for responsive UX without a server roundtrip.

```python
Input(
    placeholder="Type and press Enter",
    on_keydown=ctx.js(
        '''
        if (event.key === 'Enter') {
            const label = document.getElementById('js-enter-status');
            if (label) label.textContent = `Enter pressed: ${event.value || ''}`;
        }
        '''
    ),
)
```

## `ctx.js` calling Python (refast.invoke)

Use JavaScript to filter events client-side, then call a Python callback only when needed.

```python
async def on_enter(ctx: Context, value: str = ""):
    await ctx.update_text("js-invoke-status", f"Python received: {value}")

Input(
    on_keydown=ctx.js(
        '''
        if (event.key === 'Enter') {
            refast.invoke(args.on_submit, { value: event.value });
        }
        ''',
        on_submit=ctx.callback(on_enter),
    ),
)
```

## Chaining actions (serial vs parallel)

Fire multiple actions from one event. Default mode is serial; set `mode="parallel"` to
run them simultaneously.

```python
# Serial (default)
Button(
    "Serial chain",
    on_click=ctx.chain([
        ctx.callback(clear_chain_log),
        ctx.callback(chain_record, message="Serial step 1", delay=0.15),
        ctx.callback(chain_record, message="Serial step 2", delay=0.15),
    ]),
)

# Parallel
Button(
    "Parallel chain",
    on_click=ctx.chain([
        ctx.callback(clear_chain_log),
        ctx.chain([
            ctx.callback(chain_record, message="Parallel A (fast)", delay=0.05),
            ctx.callback(chain_record, message="Parallel B (slower)", delay=0.25),
        ], mode="parallel"),
    ], mode="serial"),
)
```

### Live demo: ctx.chain

Serial runs actions one-by-one; parallel fires them together.

Run a chain to see events here.

## Event Modifiers — `stop_propagation` & `prevent_default`

By default, DOM interactions follow standard browser rules: click events bubble up through ancestor components, anchor tags navigate to their `href`, and pressing `Enter` in text inputs can trigger form submissions.

Refast provides native boolean modifiers on callback and action definitions so you can control event bubbling and default browser behaviors without complex JavaScript boilerplate:

- **`stop_propagation=True`**: Prevents the event from bubbling up through the DOM tree (invokes `event.stopPropagation()` on the client). Parent components will not receive or fire handlers for this event.
- **`prevent_default=True`**: Suppresses the browser's default action for the event (invokes `event.preventDefault()` on the client). For example, prevents `<a>` links from navigating, forms from submitting on `Enter`, or page scrolling. Your Refast callback or JS action still executes normally.

### Supported Action Types

Modifiers can be set on **all five** Refast action creation methods:

| Method | Usage Example |
|--------|---------------|
| `ctx.callback()` | `ctx.callback(my_func, stop_propagation=True, prevent_default=True)` |
| `ctx.js()` | `ctx.js("alert('hi')", stop_propagation=True, prevent_default=True)` |
| `ctx.bound_js()` | `ctx.bound_js("my-id", "method", stop_propagation=True)` |
| `ctx.save_prop()` | `ctx.save_prop("field", stop_propagation=True)` |
| `ctx.chain()` | `ctx.chain([...], stop_propagation=True, prevent_default=True)` |

> [!NOTE]
> **Action Chains (`ctx.chain`)**: Modifiers can be set on the outer `ctx.chain()` or on any nested action inside the chain. Refast recursively inspects the entire action hierarchy — if any action in the chain specifies `stopPropagation` or `preventDefault`, that modifier is applied before execution.

---

### Core Patterns

#### 1. Controlling Event Bubbling (`stop_propagation`)
When an inner component is nested inside an outer clickable container (e.g. a button inside a clickable card), clicks on the inner component bubble up to trigger the parent's handler unless propagation is halted:

```python
# The outer Container handler triggers for any clicks inside it
Container(
    on_click=ctx.callback(handle_outer_click),
    class_name="p-4 border rounded",
    children=[
        # Bubbles: fires handle_inner_bubble THEN handle_outer_click
        Button("Normal Click (Bubbles)", on_click=ctx.callback(handle_inner_bubble)),

        # Stops propagation: fires ONLY handle_inner_stop
        Button(
            "Stop Propagation",
            on_click=ctx.callback(handle_inner_stop, stop_propagation=True),
        ),
    ],
)
```

#### 2. Suppressing Default Browser Actions (`prevent_default`)
Intercept link clicks or form submissions to run server-side Python logic or client JS without leaving the page or triggering a reload:

```python
# Normal navigation occurs: browser opens https://example.com
Link("Visit Example", href="https://example.com")

# Suppresses navigation: browser stays on page, Python callback runs
Link(
    "Execute Server Callback Only",
    href="https://example.com",
    on_click=ctx.callback(handle_link_action, prevent_default=True),
)
```

#### 3. Inspecting Modifier State in Parent Handlers
When an event bubbles up to a parent container, the parent handler can inspect whether child elements prevented default behavior or stopped propagation:

- **Python (`ctx.event_data`)**:
  ```python
  async def handle_parent_click(ctx: Context):
      # True if a child event handler set prevent_default=True
      default_prevented = ctx.event_data.get("default_prevented", False)
      # True if a child event handler set stop_propagation=True
      propagation_stopped = ctx.event_data.get("propagation_stopped", False)

      print(f"Parent received event: default_prevented={default_prevented}")
  ```

- **JavaScript (`ctx.js`)**:
  ```javascript
  if (event.defaultPrevented) {
      console.log("Child prevented default action");
  }
  if (event.propagationStopped) {
      console.log("Child stopped propagation");
  }
  ```

#### 4. Keyboard KeyDown Interception (`ctx.js`)
Suppress default form submission or newline behaviors on key presses (such as `Enter`):

```python
Input(
    placeholder="Press Enter here...",
    on_keydown=ctx.js(
        "if (event.key === 'Enter') { refast.invoke(args.on_enter); }",
        on_enter=ctx.callback(handle_keydown_enter),
        prevent_default=True,
    ),
)
```

### Live demo: stop_propagation and prevent_default

Click the dashed card area, the buttons inside it, or the link to test propagation and default action suppression.

Outer Container (Click anywhere inside this dashed area)

Event log: click any interactive element above to see events fire.

## Typed Events & Payload Validation

Refast supports Pydantic models for structured event validation. You can type-annotate callbacks with Pydantic models, or listen for custom events via `@ui.on()`. If validation fails, Refast catches the validation error and can invoke custom error handlers or notify the user.

### 1. Typed Callbacks with Pydantic Models

Annotate your callback's parameter with a Pydantic model. Refast will parse and validate the incoming client payload automatically before executing the handler function.

```python
from pydantic import BaseModel, Field
from refast import Context

class SearchQueryPayload(BaseModel):
    query: str = Field(..., min_length=2, description="Search query text")
    limit: int = Field(10, ge=1, le=50, description="Max results")

async def run_search(ctx: Context, payload: SearchQueryPayload):
    # payload is guaranteed to be a valid SearchQueryPayload instance
    query = payload.query
    limit = payload.limit
    await ctx.show_toast(f"Searching for '{query}' (limit: {limit})", variant="success")
```

### 2. Custom Event Listeners (`@ui.on`) and Custom Error Handlers

Register event listeners with `@ui.on()` for custom socket events and attach custom error handling functions using `on_error`:

```python
from refast.events.types import Event

async def event_error_handler(ctx: Context, error: Exception, event: Event):
    await ctx.show_toast(
        message="Validation Failed",
        description="Check your inputs. Query must be at least 2 characters.",
        variant="warning",
    )

@ui.on("search:query_event", on_error=event_error_handler)
async def handle_search_event(ctx: Context, event: Event[SearchQueryPayload]):
    query = event.data.query
    limit = event.data.limit
    await ctx.show_toast(f"Typed Event Validated: {query} (Limit: {limit})")
```

## Next steps

- [State Management](https://refast.fastapicloud.dev/docs/concepts/state) — Persist data across callbacks
- [DOM Updates](https://refast.fastapicloud.dev/docs/concepts/updates) — Targeted replacements, appends, and prop updates
- [JavaScript Interop](https://refast.fastapicloud.dev/docs/concepts/js-interop) — Run browser code and call component methods

---

Part of the Refast documentation: [all pages](https://refast.fastapicloud.dev/llms.txt), [everything on one page](https://refast.fastapicloud.dev/llms-full.txt), [search](https://refast.fastapicloud.dev/api/search?q=save_prop).
