| 1 |
""" |
| 2 |
Observers are objects listening to EventDispatchers. |
| 3 |
|
| 4 |
They are mostly used as bases for UIs in the context of the DC. |
| 5 |
""" |
| 6 |
|
| 7 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 8 |
#c |
| 9 |
#c This program is free software, covered by the GNU GPL. See the |
| 10 |
#c COPYING file in the source distribution. |
| 11 |
|
| 12 |
from gavo.utils.dachstypes import Callable |
| 13 |
from gavo.base.events import EventDispatcher |
| 14 |
|
| 15 |
|
| 16 |
def listensTo(*args: str) -> Callable: |
| 17 |
"""a decorator to make a method listen to a set of events. |
| 18 |
|
| 19 |
It receives one or more event names. |
| 20 |
""" |
| 21 |
def deco(meth: Callable) -> Callable: |
| 22 |
meth.listensTo = args # type: ignore # setting a sentinel |
| 23 |
return meth |
| 24 |
return deco |
| 25 |
|
| 26 |
|
| 27 |
class ObserverBase: |
| 28 |
"""a base class for observers. |
| 29 |
|
| 30 |
Observers have methods listening to certain events. Use the listen |
| 31 |
decorator above to make the connections. The actual event subscriptions |
| 32 |
are done in the constructor. |
| 33 |
|
| 34 |
The signature of the listeners always is:: |
| 35 |
|
| 36 |
listener(dispatcher, arg) -> ignored |
| 37 |
|
| 38 |
dispatcher is the EventDispatcher instance propagating the event. It |
| 39 |
has lots of useful attributes explained in base.event's notifyXXX docstrings. |
| 40 |
|
| 41 |
You can listen to anything that has a notify method in the EventDispatcher. |
| 42 |
|
| 43 |
Observers are used in DaCHS for both logging and notification of users. |
| 44 |
Code generally does not use them directly but instead calls |
| 45 |
base.ui.notifyXXX; where you don't have base, try the slower |
| 46 |
utils.misctricks.sendUIEvent. |
| 47 |
""" |
| 48 |
def __init__(self, dispatcher: EventDispatcher) -> None: |
| 49 |
self.dispatcher = dispatcher |
| 50 |
for name in dir(self): |
| 51 |
att = getattr(self, name) |
| 52 |
if hasattr(att, "listensTo"): |
| 53 |
for ev in att.listensTo: |
| 54 |
dispatcher.subscribe(ev, att) |