Guest User

Untitled

a guest
Feb 23rd, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. ```python
  2. class EventEmitter:
  3. topics = {}
  4.  
  5. def on(self, topic, handler):
  6. if topic not in self.topics:
  7. self.topics[topic] = []
  8. self.topics[topic].append(handler)
  9.  
  10. def off(self, topic, handler):
  11. if topic not in self.topics or handler not in self.topics[handler]:
  12. return
  13. self.topics[topic].remove(handler)
  14.  
  15. def emit(self, topic, **keywords):
  16. if topic not in self.topics:
  17. return
  18. for handler in self.topics[topic]:
  19. handler(**keywords)
  20. ```
  21.  
  22. とりあえずEventを登録、削除、発火できる。
  23.  
  24.  
  25. ```python
  26. class Dispatcher:
  27. def __init__(self):
  28. self.emitter = EventEmitter()
  29.  
  30. def dispatch(self, topic, **keywords):
  31. self.emitter.emit(topic, **keywords)
  32.  
  33. def on(self, topic, handler):
  34. self.emitter.on(topic, handler)
  35.  
  36. def off(self, topic, handler):
  37. self.emitter.off(topic, handler)
  38. ```
  39.  
  40. Pub/SubでいうPub役。
  41. DispatcherにEventHandlerを登録しておくとdispatchされた際にまとめて実行する。
  42.  
  43. Fluxでいうとtopic+keywords=Actionを受け取ってる。
  44. ViewはStoreを、StoreはViewを知らなくてもDispatcherを介してやりとりできるが、だいたいViewはStoreを参照してデータを得る。
  45. Dispatcher経由で知らせるのは画面表示を更新するタイミング。
  46.  
  47.  
  48. ```python
  49. class ByeStore:
  50. def __init__(self, dispatcher):
  51. self.greeting = ''
  52. dispatcher.on('greet', self.bye)
  53.  
  54. def bye(self, name=''):
  55. self.greeting = 'Bye, {}!'.format(name)
  56.  
  57.  
  58. class HelloStore:
  59. def __init__(self, dispatcher):
  60. self.greeting = ''
  61. dispatcher.on('greet', self.hello)
  62.  
  63. #デフォルト値を与えないと**keywordsに入らない
  64. #def hello(self, name):
  65. def hello(self, name=''):
  66. self.greeting = 'Hello {}!'.format(name)
  67. ```
  68.  
  69. Pub/SubでいうSub役。
  70. Actionの内容をもとに自分自身を更新するEventHandlerをDispatcherに登録する。
  71.  
  72. せっかくPythonなのでオプション引数で実装してみた。
  73. デフォルト値を外してみるとまた挙動が変わる。
  74.  
  75.  
  76. ```python
  77. def testDispatcher():
  78. dispatcher = Dispatcher()
  79. a = ByeStore(dispatcher)
  80. b = HelloStore(dispatcher)
  81. assert not a.greeting
  82. assert not b.greeting
  83. dispatcher.dispatch('greet', name='John')
  84. #handlerにageが用意されていないのでエラーになる
  85. #dispatcher.dispatch('greet', age=18, name='John')
  86. assert a.greeting == 'Bye, John!'
  87. assert b.greeting == 'Hello John!'
  88.  
  89. #エラーが出なければ正常
  90. testDispatcher()
  91. ```
Add Comment
Please, Sign In to add comment