Eventbus overview
You can register your events and event handlers with the Eventbus
package:
Usage
You can use your own events directly with an event handler that you register on the eventbus
.
-
Import the
system.eventbus
package:from system.eventbus import eventbus
-
Define an event:
class SpecialEvent: def __init__(self): pass def __str__(self): return "special event"
-
Define a synchronous or asynchronous method to be called when the event occurs:
def handle_event(self, event): # do something
async def handle_event_async(self, event): # do something
-
Register your event handler, for example in the
__init__
method of your app with the event and the event handler. Depending on whether the event handler is a synchronous or asynchronous method callon()
oron_async()
:def __init__(self): eventbus.on(SpecialEvent, self.handle_event, self.app)
def __init__(self): eventbus.on_async(SpecialEvent, self.handle_event_async, self.app)
-
Add code to emit the event, for example in your app's
update()
method. Depending on whether the event handler is a synchronous or asynchronous method callemit()
oremit_async()
:def update(self, delta): # If something happens eventbus.emit(SpecialEvent())
async def update(self, delta): # If something happens await eventbus.emit_async(SpecialEvent())
-
Remove the event handler when the app is minimised or closed.
eventbus.remove(SpecialEvent, self.handle_event, self.app)
Warning
Make sure you remove the event handler when the app is minimised or closed!
You can see a more comprehensive example in dialog.py
or pingpong_app.py
.
Methods
You can use the following methods on the eventbus
:
Method | Description | Arguments | Returns |
---|---|---|---|
on(event_type, event_handler, app) | Register an event for an app alongside the synchronous handler to be called when the event fires. |
| None |
on_async(event_type, event_handler, app) | Register an event for an app alongside the asynchronous handler to be called when the event fires. |
| None |
emit(event) | Emit an event to the eventbus. The handler for the event must be synchronous. | event : The event, for example ButtonDownEvent . An event object must have the methods __init__() and __str__() . | None |
emit_async(event) | Emit an event to the eventbus. The handler for the event must be asynchronous. | event : The event, for example ButtonDownEvent . An event object must have the methods __init__() and __str__() . | None |
remove(event_type, event_handler, app) | Remove the event for an app from the eventbus. |
| None |