observer.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from twisted.internet import reactor
  2. class Observer(object):
  3. def __init__(self):
  4. self.dispatch = {}
  5. def emit(self, signal, *msg):
  6. """ emit a signal, return True if sent somewhere. """
  7. if signal in self.dispatch:
  8. # key exists, but is there anything in the list?
  9. if self.dispatch[signal]:
  10. # Yes there is.
  11. for listener in self.dispatch[signal]:
  12. reactor.callLater(0, listener, *msg)
  13. return True
  14. return False
  15. return False
  16. def connect(self, signal, func):
  17. """ Connect a signal to a given function. """
  18. if not signal in self.dispatch:
  19. self.dispatch[signal] = []
  20. self.dispatch[signal].append(func)
  21. def disconnect(self, signal, func):
  22. """ Disconnect a signal with a certain function. """
  23. if signal in self.dispatch:
  24. self.dispatch[signal].remove(func)
  25. if len(self.dispatch[signal]) == 0:
  26. self.dispatch.pop(signal)
  27. def save(self):
  28. """ Save the current dispatch, and clears it. """
  29. ret = dict(self.dispatch)
  30. self.dispatch = {}
  31. return ret
  32. def load(self, dispatch):
  33. """ Load/restore the dispatch. """
  34. assert not dispatch is None
  35. self.dispatch = dict(dispatch)