-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathevent.py
56 lines (51 loc) · 1.71 KB
/
event.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
Defines a mix-in class for events.
"""
import threading, traceback
from tools import startdaemon
class EventSource(object):
"""
This is a mix-in for classes that want to produce events for other modules
to subscribe to.
"""
__calls = None
def __init__(self, *p, **kw):
super(EventSource, self).__init__(*p, **kw)
self.__calls = {}
def connect(self, event, func, thread=True):
"""es.connect(str, callable, [bool])
Registers your callback against the named event. If thread is True, the
callback will be called in a new thread.
"""
event = str(event)
e = self.__calls.setdefault(event, {})
e[func] = thread
def disconnect(self, event, func):
"""es.disconnect(str, callable)
Removes the given callback from the named event. If it's not there,
ValueError is raised.
"""
try:
del self.__calls[event][func]
except KeyError:
raise ValueError
def emit(self, event, *p, **kw):
"""es.emit(str, ...)
Throws the event and calls the callbacks for it. Any additional
parameters are passed to the callbacks.
"""
try:
calls = self.__calls[event]
except KeyError:
return
for func, thread in calls.items():
if thread:
startdaemon(func, self, *p, **kw)
else:
try:
func(self, *p, **kw)
except KeyboardInterrupt:
raise
except:
print >> sys.stderr, "Error in event %s, ignored" % event
traceback.print_exc()