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 22:44:40 +01:00
|
|
|
return [to_camel_case(fn.__name__) 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-25 23:51:30 +01:00
|
|
|
"""trigger callback on update"""
|
|
|
|
|
|
|
|
for fn in self._callbacks:
|
2022-07-27 22:44:40 +01:00
|
|
|
if fn.__name__ == f"on_{to_snake_case(event)}":
|
|
|
|
fn(as_dataclass(event, data.get("eventData")))
|
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)
|
|
|
|
except TypeError as e:
|
|
|
|
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-25 23:51:30 +01:00
|
|
|
"""deregisters a callback from _callbacks"""
|
|
|
|
|
|
|
|
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)
|
|
|
|
except TypeError as e:
|
|
|
|
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()
|