Skip to content

Events: both directions ​

both directions

Calls return values; events do not. They suit "just tell me something happened": a button was clicked, progress moved, the window finished loading.

An event name is any string and the payload is a JSON array. The two directions use two different APIs — write them separately, never mixed:

DirectionSenderReceiver
JS → PythonAxonEvent.dispatchPYEvent({ type, args })AxonEvent.add_listener(type, fn)
Python → JSAxonEvent.dispatch_js_event(web, type, args)AxonEvent.addListener(type, fn)

Window broadcast (AxonCross.emit) is also Python → JS; see cross-window interaction.

Direction 1: JS fires → Python listens ​

app.js
import { AxonEvent } from "axon-gui";

// send only: event name + argument array
AxonEvent.dispatchPYEvent({ type: "demo:pong", args: [1, 2, 3] });   
controller.py
import threading

from axon import AxonController, AxonEvent

@AxonController("MainView")
class DemoController:
    def __init__(self) -> None:
        self.pong_log: list[list] = []
        self._lock = threading.Lock()

        # receive only: the name must match exactly what JS sent
        AxonEvent.add_listener("demo:pong", self._on_pong)           // [!code highlight]

    def _on_pong(self, *args) -> None:
        with self._lock:
            self.pong_log.append(list(args))

Listeners run on a worker thread — do not do slow work inside them; hand heavy work to a queue or back to the main thread with AxonMagicGUI.run.

Direction 2: Python fires → JS listens ​

controller.py
from axon import AxonEvent

# send only: which window, event name, payload
AxonEvent.dispatch_js_event("MainView", "demo:event", ["hello from python"])   // [!code highlight]
app.js
import { AxonEvent } from "axon-gui";

// receive only
function onEvent(text) {
  console.log("Python says:", text);
}
AxonEvent.addListener("demo:event", onEvent);                    

Streaming progress with events ​

A single call waits until it finishes; if you want the UI to see intermediate state, push events from the long-running method:

controller.py
python
def def stream(self, count: int) -> dictstream(self, count: int = 4) -> dict:
    for i in range(count):
        AxonEvent.dispatch_js_event(
            WEB, "demo:progress", [{"step": i + 1, "total": count}]
        )
        time.sleep(0.15)
    return {"done": count}
app.js
AxonEvent.addListener("demo:progress", ({ step, total }) => {
  bar.style.width = `${(step / total) * 100}%`;
});

Removing listeners ​

Keep the function you passed to addListener, otherwise you cannot remove it:

app.js
const onProgress = (p) => render(p);
AxonEvent.addListener("demo:progress", onProgress);

// on unmount, or when it is no longer needed
AxonEvent.removeListener("demo:progress", onProgress);

On the Python side: AxonEvent.remove_listener(type, fn) and AxonEvent.remove_all_listeners(type).

Built-in Qt events ​

The window itself emits events too (loadFinished, contextMenu, dragEnter, dragMove, drop, dragLeave, hide, show). They work exactly like custom events, and the receiver is always JS:

app.js
AxonEvent.addListener("loadFinished", () => console.log("page loaded"));

loadFinished fires only after the page's JS has reported in, so it can never arrive before your listener is registered — see architecture.

Hover to see the types ​

addListener() returns an unsubscribe function; the callback receives what dispatchPYEvent sent.

ts
import { 
const AxonEvent: {
    __listeners: EventListeners;
    __onceEventListenerMap: OnceEventListenerMap;
    on: <K extends AxonEventName>(type: K, listener: AxonEventListener<K>, options?: AddEventListenerOptions) => () => void;
    off: <K extends AxonEventName>(type: K, listener: AxonEventListener<K>) => void;
    ... 4 more ...;
    dispatchPYEvent({ type, args, kwargs, }: {
        type: string;
        args?: any[];
        kwargs?: Record<string, any>;
    }): Promise<unknown>;
}
AxonEvent
} from "axon-gui";
const const off: () => voidoff: () => void =
const AxonEvent: {
    __listeners: EventListeners;
    __onceEventListenerMap: OnceEventListenerMap;
    on: <K extends AxonEventName>(type: K, listener: AxonEventListener<K>, options?: AddEventListenerOptions) => () => void;
    off: <K extends AxonEventName>(type: K, listener: AxonEventListener<K>) => void;
    ... 4 more ...;
    dispatchPYEvent({ type, args, kwargs, }: {
        type: string;
        args?: any[];
        kwargs?: Record<string, any>;
    }): Promise<unknown>;
}
AxonEvent
.addListener<"demo:event">(type: "demo:event", listener: (...args: any[]) => any, options?: AddEventListenerOptions): () => voidaddListener("demo:event", (text: stringtext: string) => {
var console: Consoleconsole.Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
(text: stringtext.String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
());
}); const off: () => voidoff();

Takeaways ​

  • Two directions, two APIs: dispatchPYEvent is JS → Python, dispatch_js_event / AxonCross.emit is Python → JS;
  • event names must match exactly on both sides (demo:pong ≠ demo:Pong);
  • payloads must be JSON-representable;
  • never do slow work in a listener, and never throw from one (it is only logged, never sent back).