Source code for tagit.controller.controller
"""Controller base class.
Part of the tagit module.
A copy of the license is provided with the project.
Author: Matthias Baumgartner, 2016
"""
# IMPORTS
# INNER-MODULE IMPORTS
# EXPORTS
__all__ = ('Controller', 'DataController')
## CODE ##
[docs]class Controller(object):
"""Controller base class. Any controller receives a dict
with the *settings*, a data *model* and a *parent*.
The *parent* being None implies that the object is the
root controller.
The controller supports a simple event meachanism. You
can bind callbacks on events on a controller object and
later dispatch the event. Note that dispatching an event
only affects callback bound to the same controller instance.
>>> def callback_fu(arg1, arg2):
pass
>>>
>>> c = Controller()
>>> c.bind(event_name=callback_fu)
>>> c.dispatch('event_name', arg1, arg2)
>>> Controller().dispatch('event_name', arg1, args2) # Doesn't do anything
"""
def __init__(self, widget, settings, parent=None):
self.widget = widget
self.settings = settings
self.parent = parent
self.bindings = {}
[docs] def add_child(self, cls, wx, **kwargs):
"""Create and add a child controller.
"""
return cls(widget=wx, settings=self.settings, parent=self, **kwargs)
[docs] def get_root(self):
"""Return the top element in the controller tree.
Return the root of the tree the instance is currently attached to. If
the controller is created but not attached to a real controller tree,
the result may be unusable.
"""
while self.parent is not None:
self = self.parent
return self
###########################################################################
# POOR MAN'S EVENTS #
###########################################################################
[docs] def bind(self, **kwargs):
"""Bind a callback to an event.
>>> Controller().bind(event_name=callback_fu)
"""
for evt_name, evt_clbk in kwargs.iteritems():
if evt_name in self.bindings:
self.bindings[evt_name].append(evt_clbk)
else:
self.bindings[evt_name] = [evt_clbk]
[docs] def unbind(self, **kwargs):
"""Release an event binding. The arguments have to be identical to the
call to `bind`.
>>> c = Controller()
>>> c.bind(event_name=callback_fu)
>>> c.unbind(event_name=callback_fu)
"""
for evt_name, evt_clbk in kwargs.iteritems():
if evt_name in self.bindings:
try:
self.bindings[evt_name].remove(evt_clbk)
except ValueError:
pass
[docs] def dispatch(self, event, *args, **kwargs):
"""Dispatch an event.
Extra arguments after the *event* will be passed to the event handler>
"""
if event in self.bindings:
for clbk in self.bindings[event]:
if clbk(*args, **kwargs):
break
[docs]class DataController(Controller):
"""A controller with access to a *model*.
"""
def __init__(self, widget, model, settings, parent=None):
super(DataController, self).__init__(widget, settings, parent)
self.model = model
def add_child(self, cls, wx, **kwargs):
return cls(widget=wx, model=self.model, settings=self.settings, parent=self, **kwargs)
## EOF ##