introduce a new CubicwebEventManager
authorAdrien Di Mascio <Adrien.DiMascio@logilab.fr>
Tue, 04 Aug 2009 18:40:47 +0200
changeset 2683 52b1a86c1913
parent 2682 0188a4a02403
child 2684 c84691380dd4
introduce a new CubicwebEventManager Typical emit usage: >>> from cubicweb import CW_EVENT_MANAGER >>> CW_EVENT_MANAGER.emit('after-source-reload') Typical bind usage: >>> from cubicweb import CW_EVENT_MANAGER >>> CW_EVENT_MANAGER.bind('after-source-reload', mycallback)
__init__.py
--- a/__init__.py	Tue Aug 04 17:39:02 2009 +0200
+++ b/__init__.py	Tue Aug 04 18:40:47 2009 +0200
@@ -317,3 +317,34 @@
 def underline_title(title, car='-'):
     return title+'\n'+(car*len(title))
 
+
+class CubicWebEventManager(object):
+    """simple event / callback manager.
+
+    Typical usage to register a callback::
+
+      >>> from cubicweb import CW_EVENT_MANAGER
+      >>> CW_EVENT_MANAGER.bind('after-source-reload', mycallback)
+
+    Typical usage to emit an event::
+
+      >>> from cubicweb import CW_EVENT_MANAGER
+      >>> CW_EVENT_MANAGER.emit('after-source-reload')
+
+    emit() accepts an additional context parameter that will be passed
+    to the callback if specified (and only in that case)
+    """
+    def __init__(self):
+        self.callbacks = {}
+
+    def bind(self, event, callback, *args, **kwargs):
+        self.callbacks.setdefault(event, []).append( (callback, args, kwargs) )
+
+    def emit(self, event, context=None):
+        for callback, args, kwargs in self.callbacks.get(event, ()):
+            if context is None:
+                callback(*args, **kwargs)
+            else:
+                callback(context, *args, **kwargs)
+
+CW_EVENT_MANAGER = CubicWebEventManager()