Skip to content

Instantly share code, notes, and snippets.

@MelleB
Created April 30, 2016 20:22
Show Gist options
  • Save MelleB/4036d17f03dbbd126bb27c8dc05b4822 to your computer and use it in GitHub Desktop.
Save MelleB/4036d17f03dbbd126bb27c8dc05b4822 to your computer and use it in GitHub Desktop.
A simple global event emitter in Python
_callbacks = {}
class Event():
@staticmethod
def on(event_name, f):
_callbacks[event_name] = _callbacks.get(event_name, []) + [f]
return f
@staticmethod
def emit(event_name, *data):
[f(*data) for f in _callbacks.get(event_name, [])]
@staticmethod
def off(event_name, f):
_callbacks.get(event_name, []).remove(f)
if __name__ == "__main__":
count = 0
def addX(x):
global count
count += x
Event.on('add', addX)
assert('add' in _callbacks)
Event.emit('add', 2)
assert(count == 2)
Event.off('add', addX)
Event.emit('add', 2)
assert(count == 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment