Basic Event Loop in Python [duplicate]

寵の児 提交于 2019-12-03 15:11:21

An event loop is a loop which handles / deals with events.

An event is something that occurs in the system where some code parts might be interested in.

At the beginning, all components register for events, and after that, an init event is fired:

I am just providing raw code here:

listeners = [component1, component2, component3]
eventqueue.add(InitEvent())
while True:
    event = eventqueue.pop()
    for listener in listeners:
        listener.handle_event(event)

How an eventqueue is implemented and what the Event() class hierarchy looks like is left as an exercise for the reader. Take care about using threading.(R)Locks etc. for the .pop() method.

Additionally, you could have separate listener lists for each event type. An event could thus be "fired" by just calling it (or its .fire() method) and have a mechanism to identify all its own and parent's listeners in order to inform them about the event.

In any case, the listeners then can decide on their own what to do with and according to the event.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!