# Events

Components communicate through events. Emit events from one component that others can receive,
or dispatch browser events that JavaScript can listen to.

## Broadcasting events

Use `emit(event_name, payload)` to broadcast an event to every component on the page. The sender doesn't know or care who is listening, any component with a matching method handles it. That loose coupling is ideal when one action, a checkout, a finished background job, a saved form, needs unrelated parts of the UI to react.

Buy the license below. The `Purchase` component emits `notification_created`, and the bell in the navbar, a completely separate `Notification` component, picks up the broadcast: its unread count ticks up, and the dropdown shows the message.

```interlace-demo
Storefront
```

## Targeted events

Use `emit_to(component_name, event_name, payload)` to send events to a specific component.
Only components matching the name will receive the event.

Send targeted events. Only the specified component receives each event.

```interlace-demo
EventsEmitTo
EventsTargetAlpha
EventsTargetBeta
```

## Browser events

Use `dispatch_browser_event(event_name, payload)` to dispatch a CustomEvent on the DOM.
Any JavaScript can listen, including Alpine.js, vanilla JS, or other frameworks.

Interlace dispatches a browser event that Alpine.js receives.

```interlace-demo
EventsBrowser
```

Browser events use `window.dispatchEvent()` with `CustomEvent`.
Access payload via `$event.detail` in Alpine.js or `event.detail` in vanilla JS.

## Event methods

| Method | Description |
|---|---|
| emit(event_name, payload) | Broadcast to all components |
| emit_to(component_name, event_name, payload) | Send to specific component by name |
| dispatch_browser_event(event_name, payload) | Dispatch DOM CustomEvent for JavaScript |

## How to listen

Define a method with the same name as the event:

```python
class MyComponent(Component):
    message: str = ""

    def notification_sent(self, payload):
        # Method name = event name
        self.message = payload['text']
```

When `notification_sent` is emitted, Interlace calls this method automatically with the payload.

> **Component Communication**
>
> Events enable loosely coupled components. A form can emit "user_saved" without knowing
> which components care. Multiple listeners can respond independently.
