Created
April 30, 2016 20:22
-
-
Save MelleB/4036d17f03dbbd126bb27c8dc05b4822 to your computer and use it in GitHub Desktop.
A simple global event emitter in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_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