baseimage-tutorial-framework/tfw/internals/callback_mixin.py

36 lines
1.1 KiB
Python
Raw Permalink Normal View History

from functools import partial
from .lazy import lazy_property
class CallbackMixin:
@lazy_property
def _callbacks(self):
# pylint: disable=no-self-use
return []
def subscribe_callback(self, callback, *args, **kwargs):
2018-04-18 17:44:26 +00:00
"""
Subscribe a callable to invoke once an event is triggered.
:param callback: callable to be executed on events
:param args: arguments passed to callable
:param kwargs: kwargs passed to callable
2018-04-18 17:44:26 +00:00
"""
fun = partial(callback, *args, **kwargs)
self._callbacks.append(fun)
def subscribe_callbacks(self, *callbacks):
"""
Subscribe a list of callbacks to incoke once an event is triggered.
:param callbacks: callbacks to be subscribed
"""
for callback in callbacks:
self.subscribe_callback(callback)
def unsubscribe_callback(self, callback):
self._callbacks.remove(callback)
def _execute_callbacks(self, *args, **kwargs):
for callback in self._callbacks:
callback(*args, **kwargs)