forked from elvisfernandes/makemachine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevents.py
More file actions
56 lines (48 loc) · 1.6 KB
/
events.py
File metadata and controls
56 lines (48 loc) · 1.6 KB
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
#!/usr/bin/env python
from copy import deepcopy, copy
class Event():
INIT = "init"
CHANGE = "change"
OPEN = "open"
CLOSE = "close"
ACTIVATE = "activate"
COMPLETE = "complete"
DEACTIVATE = "de_activate"
def __init__( self, type ):
self.type = type
self.target = None
self.data = None
class EventDispatcher():
def __init__(self):
self.map = {}
'''
- Adds an event handler by binding it to an event type
'''
def push_handler( self, type, handler ):
if type not in self.map:
self.map[type] = [ handler ]
else:
self.map[type].append( handler )
'''
- Remove an event handler
'''
def pop_handler( self, type, handler ):
if type in self.map:
handlers = self.map[type]
for h in handlers:
if handler == h:
handlers.remove(h)
'''
- Invoke each handler bound to the dispatched event
- uses deepcopy to handle use case wherein new hanlders are added to
- within other handlers, causing lengths of dictionaries to change and errors to be thrown
'''
def dispatch_event( self, event ):
type = event.type
event.target = self
# -- creating copy to prevent length of handlers from changing if handlers are added within other handlers
clone = deepcopy( self.map )
for type in clone:
handlers = self.map[type]
for handler in handlers:
handler( event )