| 1 |
|
|---|
| 2 |
|
|---|
| 3 |
import types |
|---|
| 4 |
|
|---|
| 5 |
__version__ = "$Revision$" |
|---|
| 6 |
__author__ = "Arjan Molenaar" |
|---|
| 7 |
__date__ = "2002-08-28" |
|---|
| 8 |
|
|---|
| 9 |
class Signal: |
|---|
| 10 |
"""The signal class is an implementation of the Observer pattern. |
|---|
| 11 |
|
|---|
| 12 |
It can be used to send signals to every function or method that connected |
|---|
| 13 |
to the signal object, with a variable amount of parameters. Note that the |
|---|
| 14 |
owner of the Signal instance should define a protocol for notifying the |
|---|
| 15 |
observers. The subject should provide methods for connecting and |
|---|
| 16 |
disconnecting observers (preferably 'connect()' and 'disconnect()'. |
|---|
| 17 |
""" |
|---|
| 18 |
|
|---|
| 19 |
def __init__(self): |
|---|
| 20 |
|
|---|
| 21 |
self.__signals = [ ] |
|---|
| 22 |
|
|---|
| 23 |
|
|---|
| 24 |
|
|---|
| 25 |
|
|---|
| 26 |
|
|---|
| 27 |
|
|---|
| 28 |
def connect (self, signal_handler, *data): |
|---|
| 29 |
"""Connect to the object. You should provide a signal handler and a |
|---|
| 30 |
bunch of parameters that should be passed to the signal handler. |
|---|
| 31 |
""" |
|---|
| 32 |
|
|---|
| 33 |
self.__signals.append ((signal_handler,) + data) |
|---|
| 34 |
|
|---|
| 35 |
|
|---|
| 36 |
def disconnect (self, signal_handler): |
|---|
| 37 |
"""Disconnect the signal_handler (observer). |
|---|
| 38 |
""" |
|---|
| 39 |
self.__signals = filter (lambda o: o[0] != signal_handler, |
|---|
| 40 |
self.__signals) |
|---|
| 41 |
|
|---|
| 42 |
def disconnect_by_data (self, *data): |
|---|
| 43 |
|
|---|
| 44 |
self.__signals = filter (lambda o: o[1:] != data, |
|---|
| 45 |
self.__signals) |
|---|
| 46 |
|
|---|
| 47 |
|
|---|
| 48 |
def emit (self, *keys): |
|---|
| 49 |
"""Emit the signal. A set of parameters can be defined that will be |
|---|
| 50 |
passed to the signal handler. Those parameters will be set before |
|---|
| 51 |
the parameters provided through the connect() method. |
|---|
| 52 |
In case there are queued emisions, this function will queue the |
|---|
| 53 |
signal emision too. |
|---|
| 54 |
|
|---|
| 55 |
Note that you should define how many parameters are provided by the |
|---|
| 56 |
owner of the signal. |
|---|
| 57 |
""" |
|---|
| 58 |
|
|---|
| 59 |
for signal in self.__signals: |
|---|
| 60 |
signal_handler = signal[0] |
|---|
| 61 |
data = keys + signal[1:] |
|---|
| 62 |
apply(signal_handler, data) |
|---|
| 63 |
|
|---|