Skip to content

Instantly share code, notes, and snippets.

@westmark
Created June 27, 2012 08:47
Show Gist options
  • Save westmark/3002515 to your computer and use it in GitHub Desktop.
Save westmark/3002515 to your computer and use it in GitHub Desktop.
Dynamic Event Manager
class EventGroup(object):
def __init__(self):
self._sub_events = {}
self._listeners = set()
self._batched = False
self._batched_args = []
def __getitem__(self, name):
return self._sub_events.setdefault(name.lower(), EventGroup())
def bind(self, callback):
self._listeners.add(callback)
def unbind(self, callback):
if callback in self._listeners:
self._listeners.remove(callback)
def fire(self, *args, **kvargs):
if self._batched:
self._batched_args.append((args, kvargs))
else:
for callback in self._listeners:
callback(*args, **kvargs)
def begin_batch(self):
self._batched = True
self._batched_args = []
def fire_batch(self, *args, **kvargs):
if self._batched:
self._batched = False
self._batched_args = []
self.fire(*args, **kvargs)
@property
def batched_args(self):
return self._batched_args
__getattr__ = __getitem__
class EventManager(object):
def __init__(self):
self._events = EventGroup()
@property
def events(self):
return self._events
def get(self, name, strict=False):
evt_cnt = self.events
for n in name.lower().split('.'):
if strict:
if n not in evt_cnt._sub_events:
return None
evt_cnt = evt_cnt[n]
return evt_cnt
def exists(self, name):
exists, search_in = True, self._events
for n in name.lower().split('.'):
if n in search_in._sub_events.keys():
search_in = search_in[n]
else:
exists = False
break
return exists
if __name__ == '__main__':
mgr = EventManager()
def callback():
print 'callback'
mgr.events.mouse.moved.bind(callback)
mgr.events.mouse.moved.fire()
mgr.get('mouse.moved').fire()
print mgr.exists('mouse.moved')
print mgr.exists('mouse.moved.yay')
print mgr.exists('mouse.move.yay')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment