Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```python
- class EventEmitter:
- topics = {}
- def on(self, topic, handler):
- if topic not in self.topics:
- self.topics[topic] = []
- self.topics[topic].append(handler)
- def off(self, topic, handler):
- if topic not in self.topics or handler not in self.topics[handler]:
- return
- self.topics[topic].remove(handler)
- def emit(self, topic, **keywords):
- if topic not in self.topics:
- return
- for handler in self.topics[topic]:
- handler(**keywords)
- ```
- とりあえずEventを登録、削除、発火できる。
- ```python
- class Dispatcher:
- def __init__(self):
- self.emitter = EventEmitter()
- def dispatch(self, topic, **keywords):
- self.emitter.emit(topic, **keywords)
- def on(self, topic, handler):
- self.emitter.on(topic, handler)
- def off(self, topic, handler):
- self.emitter.off(topic, handler)
- ```
- Pub/SubでいうPub役。
- DispatcherにEventHandlerを登録しておくとdispatchされた際にまとめて実行する。
- Fluxでいうとtopic+keywords=Actionを受け取ってる。
- ViewはStoreを、StoreはViewを知らなくてもDispatcherを介してやりとりできるが、だいたいViewはStoreを参照してデータを得る。
- Dispatcher経由で知らせるのは画面表示を更新するタイミング。
- ```python
- class ByeStore:
- def __init__(self, dispatcher):
- self.greeting = ''
- dispatcher.on('greet', self.bye)
- def bye(self, name=''):
- self.greeting = 'Bye, {}!'.format(name)
- class HelloStore:
- def __init__(self, dispatcher):
- self.greeting = ''
- dispatcher.on('greet', self.hello)
- #デフォルト値を与えないと**keywordsに入らない
- #def hello(self, name):
- def hello(self, name=''):
- self.greeting = 'Hello {}!'.format(name)
- ```
- Pub/SubでいうSub役。
- Actionの内容をもとに自分自身を更新するEventHandlerをDispatcherに登録する。
- せっかくPythonなのでオプション引数で実装してみた。
- デフォルト値を外してみるとまた挙動が変わる。
- ```python
- def testDispatcher():
- dispatcher = Dispatcher()
- a = ByeStore(dispatcher)
- b = HelloStore(dispatcher)
- assert not a.greeting
- assert not b.greeting
- dispatcher.dispatch('greet', name='John')
- #handlerにageが用意されていないのでエラーになる
- #dispatcher.dispatch('greet', age=18, name='John')
- assert a.greeting == 'Bye, John!'
- assert b.greeting == 'Hello John!'
- #エラーが出なければ正常
- testDispatcher()
- ```
Add Comment
Please, Sign In to add comment