JavaScript Interop
Communicate between Python components and JavaScript code.
Dispatch browser events
Send custom browser events from Python that JavaScript can listen to.
class ToastDemo(Component):
def on_save(self):
self.dispatch_browser_event("toast", {"message": "Saved successfully", "kind": "success"})
def on_delete(self):
self.dispatch_browser_event("toast", {"message": "Item deleted", "kind": "error"})
def inline_template(self):
return """
<div x-data="{ toasts: [],
add(d) { const id = Date.now()+Math.random(); this.toasts.push({id, ...d});
setTimeout(() => this.remove(id), 3000); },
remove(id) { this.toasts = this.toasts.filter(t => t.id !== id); } }"
@toast.window="add($event.detail)">
<button lace:click="on_save">Save</button>
<button lace:click="on_delete">Delete</button>
<!-- a real toast: fixed bottom-right, stacked, auto-dismiss -->
<div class="fixed bottom-4 right-4 z-50 flex flex-col gap-2 items-end">
<template x-for="t in toasts" :key="t.id">
<div x-transition
class="flex items-center gap-3 rounded-lg px-4 py-3 shadow-lg text-white"
:class="t.kind === 'error' ? 'bg-red-600' : 'bg-gray-900'">
<span x-text="t.message"></span>
<button @click="remove(t.id)">×</button>
</div>
</template>
</div>
</div>
"""
class Notification(Component):
def show_alert(self):
self.dispatch_browser_event('alert', {
'message': 'Hello from Python!',
'type': 'success'
})
// 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
<div x-data>
<button @click="$set('status', 'active')">Activate</button>
</div>
$call - call a method (with optional args)
<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.
<div x-data>
<span x-text="$lace.prop"></span>
<button @click="$lace.prop = 'world'">Update</button>
</div>
Within loops (e.g. sortable lists),
$item, $position and $key give the current
item, its index, and its key.
Call JavaScript from Python
class Map(Component):
def update_location(self, lat, lng):
# Call the client-side function updateMap(lat, lng)
self.js_call("updateMap", lat, lng)
<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:
<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>