Created
November 25, 2013 22:57
-
-
Save dplyukhin/7650430 to your computer and use it in GitHub Desktop.
'lil 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
class EventEmitter: | |
"""Create listeners on an object""" | |
def __init__(self): | |
self._events = {} | |
def on(self, event, callback): | |
"""Execute callback when event is emitted. Returns an id for deletion. | |
event {String} | |
callback {function} | |
""" | |
if event not in self._events: | |
self._events[event] = [] | |
self._events[event].append(callback) | |
return self._events[event].index(callback) | |
def once(self, event, callback): | |
"""Execute callback only once at the event, then destroys itself. Returns an id for deletion. | |
""" | |
i = self.on(event, callback) | |
def self_destruct(): | |
callback() | |
self._events[event][i] = None | |
self._events[event][i] = self_destruct | |
return i | |
def emit(self, event): | |
"""Execute every callback tied to the event. | |
""" | |
if event in self._events: | |
# Execute every non-null callback | |
[cb() for cb in self._events[event] if cb] | |
def off(self, event, i): | |
"""Remove a specific callback by id. | |
""" | |
if (event in self._events and | |
len(self._events[event]) > i): | |
self._events[event][i] = None | |
#### Testing #### | |
evan = EventEmitter() | |
def ouch(): | |
print("Ow!") | |
# Every time 'punch' occurs, ouch will be called | |
# The integer e stores the index of our callback for removal later | |
print("\n Evan will react to each punch") | |
e = evan.on('punch', ouch) | |
evan.emit('punch') | |
evan.emit('punch') | |
# Protest will be added to the execution list on 'punch' events | |
# But the protest will only execute once, then delete itself | |
# Notice lambda syntax is equivalent to function definition | |
print("\n Evan will protest once:") | |
evan.once('punch', lambda: print("Hey!")) | |
evan.emit('punch') # ouch and protest occur | |
evan.emit('punch') # only ouch occurs | |
print("\n Evan will no longer react:") | |
evan.off('punch', e) | |
evan.emit('punch') | |
print("\nSorry, Evan\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment