__init__.py
changeset 2683 52b1a86c1913
parent 2647 b0a2e779845c
child 2689 44f041222d0f
--- 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()