-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.py
52 lines (46 loc) · 1.6 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
''' This code part was pulled from github
and it's usage explained in author website:
http://emptypage.jp/notes/pyevent.en.html '''
class Event(object):
def __init__(self, doc=None):
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
return EventHandler(self, obj)
def __set__(self, obj, value):
pass
class EventHandler(object):
def __init__(self, event, obj):
self.event = event
self.obj = obj
def _getfunctionlist(self):
"""(internal use) """
try:
eventhandler = self.obj.__eventhandler__
except AttributeError:
eventhandler = self.obj.__eventhandler__ = {}
return eventhandler.setdefault(self.event, [])
def add(self, func):
"""Add new event handler function.
Event handler function must be defined like func(sender, earg).
You can add handler also by using '+=' operator.
"""
self._getfunctionlist().append(func)
return self
def remove(self, func):
"""Remove existing event handler function.
You can remove handler also by using '-=' operator.
"""
self._getfunctionlist().remove(func)
return self
def fire(self, earg=None):
"""Fire event and call all handler functions
You can call EventHandler object itself like e(earg) instead of
e.fire(earg).
"""
for func in self._getfunctionlist():
func(self.obj, earg)
__iadd__ = add
__isub__ = remove
__call__ = fire