| 1 |
class EventDispatcher: |
| 2 |
__event_stack = {} |
| 3 |
|
| 4 |
def register_event_type(self, event_type): |
| 5 |
"""Register an event type with the dispatcher. |
| 6 |
Registering event types allows the dispatcher to validate event handler |
| 7 |
names as they are attached and to search attached objects for suitable |
| 8 |
handlers. Each event type declaration must: |
| 9 |
1. start with the prefix `on_`. |
| 10 |
2. have a default handler in the class. |
| 11 |
""" |
| 12 |
|
| 13 |
if event_type[:3] != 'on_': |
| 14 |
raise Exception('A new event must start with "on_"') |
| 15 |
|
| 16 |
# Ensure that the user has at least declared the default handler |
| 17 |
if not hasattr(self, event_type): |
| 18 |
raise Exception(f'Missing default handler {event_type} in {self.__class__.__name__}') |
| 19 |
|
| 20 |
# Add the event type to the stack |
| 21 |
if event_type not in self.__event_stack: |
| 22 |
self.__event_stack[event_type] = [] |
| 23 |
|
| 24 |
def unregister_event_type(self, event_type): |
| 25 |
pass |
| 26 |
|
| 27 |
def bind(self, **kwargs): |
| 28 |
for key, value in kwargs.items(): |
| 29 |
assert callable(value), f'{value!r} is not callable' |
| 30 |
if key[:3] == 'on_': |
| 31 |
observers: list = self.__event_stack.get(key) |
| 32 |
if observers is None: |
| 33 |
continue |
| 34 |
observers.append(value) |
| 35 |
|
| 36 |
def unbind(self, **kwargs): |
| 37 |
"""Unbind event from callback functions with similar usage as""" |
| 38 |
|
| 39 |
for key, value in kwargs.items(): |
| 40 |
if key[:3] == 'on_': |
| 41 |
observers: list = self.__event_stack.get(key) |
| 42 |
if observers is None: |
| 43 |
continue |
| 44 |
observers.remove(value) |
| 45 |
|
| 46 |
def is_event_type(self, event_type): |
| 47 |
"""Return True if the event_type is already registered.""" |
| 48 |
return event_type in self.__event_stack |
| 49 |
|
| 50 |
def dispatch(self, event_type, *args, **kwargs): |
| 51 |
"""Dispatch an event across all the handlers added in bind/fbind(). |
| 52 |
As soon as a handler returns True, the dispatching stops. |
| 53 |
The function collects all the positional and keyword arguments and |
| 54 |
passes them on to the handlers. |
| 55 |
.. note:: |
| 56 |
The handlers are called in reverse order than they were registered |
| 57 |
with :meth:`bind`. |
| 58 |
:Parameters: |
| 59 |
`event_type`: str |
| 60 |
the event name to dispatch. |
| 61 |
.. versionchanged:: 1.9.0 |
| 62 |
Keyword arguments collection and forwarding was added. Before, only |
| 63 |
positional arguments would be collected and forwarded. |
| 64 |
""" |
| 65 |
observers: list = self.__event_stack.get(event_type) |
| 66 |
|
| 67 |
if observers: |
| 68 |
observers.reverse() |
| 69 |
for callbacks in observers: |
| 70 |
callbacks(*args, **kwargs) |
| 71 |
|
| 72 |
handler = getattr(self, event_type) |
| 73 |
return handler(*args, **kwargs) |