class Context(object): def __init__(self, *args, **kwargs): super(Context, self).__init__() self.signal = Signal() def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): self.signal.connect(receiver, sender, weak, dispatch_uid) def disconnect(self, receiver=None, sender=None, weak=True, dispatch_uid=None): self.signal.disconnect(receiver, sender, weak, dispatch_uid) def send(self, sender, **named): self.signal.send(sender, **named)
class ButtonWrapper(object): def __init__(self, node): self.node = node self.begin_singal = Signal() self.moved_singal = Signal() self.end_singal = Signal() self.node.addTouchEventListener(self._event) def _event(self, node, event): if event == 0: self.begin_singal.send(sender=self) elif event == 1: self.moved_singal.send(sender=self) elif event == 2: self.end_singal.send(sender=self) def connect_end(self, receiver, sender=None, weak=True, dispatch_uid=None): self.end_singal.connect(receiver, sender, weak, dispatch_uid)
class TextFieldWrapper(object): def __init__(self, node): self.node = node self.detect_signal = Signal() self.node.addEventListener(self._event) @property def text(self): return self.node.getString() @text.setter def text(self, t): self.node.setString(t) def connect_detect(self, receiver, sender=None, weak=True, dispatch_uid=None): self.detect_signal.connect(receiver, sender, weak, dispatch_uid) def _event(self, node, e): if e == const.EVENT_TYPE.TEXTFIELD_EVENT_DETACH_WITH_IME: self.detect_signal.send(sender=self)
# Sample of python dispatcher from dispatch import Signal log_it = Signal(providing_args=['level', 'message']) def simple_receiver(**kwargs): message, level = kwargs['message'], kwargs['level'] print 'Receiver # 1' print '\tLevel: %d, Message: %s\n' % (level, message) def picky_receiver(**kwargs): message, level = kwargs['message'], kwargs['level'] print 'Receiver # 2' if level < 2: print "\tSome unimportant message was sent. Ignoring it!\n" log_it.connect(simple_receiver) log_it.connect(picky_receiver) def a_cool_sender(): # Do something cool here # Now send a signal to all receivers log_it.send(sender='a_cool_sender', message='Hello!', level=1) a_cool_sender()
class Request(object): def __init__(self, remote_addr): self.remote_addr = remote_addr self.time_start = time.time() def enter(self): request_started.send(sender=self, remote_addr=self.remote_addr) def leave(self): time_end = time.time() request_ended.send(sender=self, time_start=self.time_start, time_end=time_end) def mycallback(signal, sender, **kwargs): print("Received signal: %s" % repr(kwargs)) if __name__ == "__main__": request_started.connect(mycallback) request_ended.connect(mycallback) request = Request("localhost") request.enter() request.leave()