2022-07-26 03:31:32 +01:00
|
|
|
from typing import Callable, Iterable, Union
|
2022-07-25 23:51:30 +01:00
|
|
|
|
2022-07-27 22:44:40 +01:00
|
|
|
from .util import as_dataclass, to_camel_case, to_snake_case
|
|
|
|
|
2022-07-25 23:51:30 +01:00
|
|
|
|
|
|
|
class Callback:
|
|
|
|
"""Adds support for callbacks"""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
"""list of current callbacks"""
|
|
|
|
|
|
|
|
self._callbacks = list()
|
|
|
|
|
|
|
|
def get(self) -> list:
|
|
|
|
"""returns a list of registered events"""
|
|
|
|
|
2022-07-27 23:19:10 +01:00
|
|
|
return [to_camel_case(fn.__name__[2:]) for fn in self._callbacks]
|
2022-07-25 23:51:30 +01:00
|
|
|
|
2022-07-26 21:47:41 +01:00
|
|
|
def trigger(self, event, data):
|
2022-07-30 16:37:07 +01:00
|
|
|
"""trigger callback on event"""
|
2022-07-25 23:51:30 +01:00
|
|
|
|
|
|
|
for fn in self._callbacks:
|
2022-07-27 22:44:40 +01:00
|
|
|
if fn.__name__ == f"on_{to_snake_case(event)}":
|
2022-07-28 11:55:05 +01:00
|
|
|
fn(as_dataclass(event, data))
|
2022-07-25 23:51:30 +01:00
|
|
|
|
2022-07-26 03:31:32 +01:00
|
|
|
def register(self, fns: Union[Iterable, Callable]):
|
2022-07-25 23:51:30 +01:00
|
|
|
"""registers callback functions"""
|
|
|
|
|
|
|
|
try:
|
2022-07-26 03:31:32 +01:00
|
|
|
iterator = iter(fns)
|
|
|
|
for fn in iterator:
|
2022-07-25 23:51:30 +01:00
|
|
|
if fn not in self._callbacks:
|
|
|
|
self._callbacks.append(fn)
|
2022-10-24 22:42:16 +01:00
|
|
|
except TypeError:
|
2022-07-25 23:51:30 +01:00
|
|
|
if fns not in self._callbacks:
|
|
|
|
self._callbacks.append(fns)
|
|
|
|
|
2022-07-27 20:49:45 +01:00
|
|
|
def deregister(self, fns: Union[Iterable, Callable]):
|
2022-07-30 16:37:07 +01:00
|
|
|
"""deregisters callback functions"""
|
2022-07-25 23:51:30 +01:00
|
|
|
|
|
|
|
try:
|
2022-07-27 20:49:45 +01:00
|
|
|
iterator = iter(fns)
|
|
|
|
for fn in iterator:
|
|
|
|
if fn in self._callbacks:
|
|
|
|
self._callbacks.remove(fn)
|
2022-10-24 22:42:16 +01:00
|
|
|
except TypeError:
|
2022-07-27 20:49:45 +01:00
|
|
|
if fns in self._callbacks:
|
|
|
|
self._callbacks.remove(fns)
|
2022-07-25 23:51:30 +01:00
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
"""clears the _callbacks list"""
|
|
|
|
|
|
|
|
self._callbacks.clear()
|