Changed event system to allow more advance listener.

See associated test for example.
main
Jonathan Grizou 12 years ago
parent 4f4a58d81c
commit 62bdf7dfad

@ -1,4 +1,4 @@
_listener = {} _listener = []
class Event(object): class Event(object):
@ -9,16 +9,14 @@ class Event(object):
""" This function sends the instance of the class, i.e. the event """ This function sends the instance of the class, i.e. the event
to be sent, to all function that listen to it. to be sent, to all function that listen to it.
""" """
if self.__class__ in _listener: for cls, f, args in _listener:
for f, args in _listener[self.__class__]: if isinstance(self, cls):
f(self, *args) f(self, *args)
@classmethod @classmethod
def listen(cls, *args): def listen(cls, *args):
def wrap(f): def wrap(f):
if cls not in _listener: _listener.append((cls, f, args))
_listener[cls] = []
_listener[cls].append((f, args))
# next step allow us to call the function itself without Event raised # next step allow us to call the function itself without Event raised
def wrapped_f(*args): def wrapped_f(*args):

@ -23,6 +23,17 @@ class AddEvent(Event):
return a + b return a + b
class Info(Event):
def __init__(self, info):
self.info = info
class SpecificInfo(Info):
def __init__(self, info, specific):
Info.__init__(self, info)
self.specific = specific
@TestEvent.listen(12, 15) @TestEvent.listen(12, 15)
def display(TestEventInstance, nb1, nb2): def display(TestEventInstance, nb1, nb2):
_output.append("%s %s %s" _output.append("%s %s %s"
@ -44,6 +55,13 @@ def do_it(AddEventInstance):
_output.append(AddEventInstance.add(17, 25)) _output.append(AddEventInstance.add(17, 25))
@Info.listen()
def test_info_instance(infoevent):
_output.append(infoevent.info)
if isinstance(infoevent, SpecificInfo):
_output.append(infoevent.specific)
class TestEvents(TestCase): class TestEvents(TestCase):
def setUp(self): def setUp(self):
@ -64,3 +82,9 @@ class TestEvents(TestCase):
addevent.send() addevent.send()
correct = [42] correct = [42]
self.assertEquals(_output, correct) self.assertEquals(_output, correct)
def test_listen_Info(self):
Info('info').send()
SpecificInfo('info', 'specific').send()
correct = ['info', 'info', 'specific']
self.assertEquals(_output, correct)

Loading…
Cancel
Save