Last active
August 29, 2015 14:19
-
-
Save x4x/c55a1966db3e786f43b3 to your computer and use it in GitHub Desktop.
enhanced assotative event handler
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
#!/usr/bin/python2.7 | |
# -*- coding: utf-8 -*- | |
class Handler(list): | |
"""minamal event hendler baste on a list | |
Usage: | |
def b(x): | |
print(x*2) | |
a= handler() | |
a.append(b) | |
# call: | |
a(3) | |
""" | |
def __call__(self, *args, **kwargs): | |
for i in self: | |
i(*args, **kwargs) | |
def __repr__(self): | |
return "Event(%s)" % list.__repr__(self) | |
class AssoziativHandler(dict): | |
"""Advanced assotative eventhandler | |
Usage: | |
a = AssoziativHandler() | |
a.add_event("test1") | |
a("test1") # call | |
print(a) # debug | |
def c(num): | |
print("test num*2= " + str(num*2)) | |
a.add_calleble("test1", c) | |
a("test1", 2) # call (slow) | |
a.calleble("test1")(2) # call (fast) | |
# kivy ex.: | |
.... | |
b_a = Button(text='A') | |
self.add_widget(b_a) | |
b_start.bind(on_press=handler.calleble("b_a")) | |
... | |
""" | |
def add_event(self, name): | |
"""add events to the handler. | |
Arguments: | |
name text for event | |
""" | |
if not name in self: | |
self[name] = Handler() | |
def bind(self, name, calleble): | |
"""add calleble object to the handler. | |
Arguments: | |
name name of event to hook the caleble | |
calleble calleble object | |
""" | |
if name in self: | |
self[name].append(calleble) | |
else: | |
self[name] = Handler([calleble]) | |
def calleble(self, name): | |
"""returns a pointer for a callback. | |
Arguments: | |
name pointer to event""" | |
if not name in self: | |
self[name] = Handler() | |
return self[name] | |
def __call__(self, name, *args, **kwargs): | |
"""manuel call of event | |
Arguments: | |
name name of event""" | |
if name in self: | |
self[name](*args, **kwargs) | |
def __repr__(self): | |
ret = "" | |
for i in self: | |
ret += "{0} Handels {1}\r\n".format( i, self[i] ) | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment