# JavaScript Interop

Communicate between Python components and JavaScript code.

## Dispatch browser events

Send custom browser events from Python that JavaScript can listen to.

```interlace-demo
ToastDemo
```

```python
class Notification(Component):
    def show_alert(self):
        self.dispatch_browser_event('alert', {
            'message': 'Hello from Python!',
            'type': 'success'
        })
```

```javascript
// Listen in JavaScript
document.addEventListener('alert', (event) => {
    const { message, type } = event.detail;
    alert(message);
});
```

## Magic methods

Inside an Alpine (`x-data`) scope, Interlace exposes magic helpers for
talking to the component directly from markup - handy for instant interactivity
without writing a dedicated method or directive.

**`$set` - set a property**

```django
<div x-data>
    <button @click="$set('status', 'active')">Activate</button>
</div>
```

**`$call` - call a method (with optional args)**

```django
<div x-data>
    <button @click="$call('save')">Save</button>
    <button @click="$call('add_tag', 'urgent')">Add tag</button>
</div>
```

**`$lace` - reactive proxy (get & set)**

Read and write component properties as if they were local Alpine state. Writes
sync back to the server.

```django
<div x-data>
    <span x-text="$lace.prop"></span>
    <button @click="$lace.prop = 'world'">Update</button>
</div>
```

Within loops (e.g. [sortable](/docs/lace-sort/) lists),
`$item`, `$position` and `$key` give the current
item, its index, and its key.

## Call JavaScript from Python

```python
class Map(Component):
    def update_location(self, lat, lng):
        # Call the client-side function updateMap(lat, lng)
        self.js_call("updateMap", lat, lng)
```

```django
<div id="map"></div>

<script>
function updateMap(lat, lng) {
    // Update map with new coordinates
    map.setCenter({ lat, lng });
}
</script>
```

## Session & connection failures

When a component request fails because the session or CSRF token expired - a login redirect,
or a `401`/`403`/`419` - Interlace shows a
*"This page has expired. Would you like to refresh?"* confirm instead of leaving the UI
half-updated. (Requests post with `redirect: "manual"`, so an auth redirect is
caught as an expiry rather than followed cross-origin into an unrecoverable
`Failed to fetch`.)

Override the hooks before components boot - for example, to send users straight to login, or
to surface your own offline banner on a network drop:

```django
<script>
  // Session/CSRF expired - replace the default confirm+reload.
  Interlace.onPageExpired = () => {
      window.location.href = "/login/?next=" + location.pathname;
  };

  // True network drop (no server response) - e.g. show an offline banner.
  Interlace.onConnectionError = (component) => { /* … */ };
</script>
```
