use defaultdict instead of dict for event engine
This commit is contained in:
parent
f538e6aa12
commit
1dc3d9d61d
@ -4,6 +4,7 @@
|
||||
from Queue import Queue, Empty
|
||||
from threading import Thread
|
||||
from time import sleep
|
||||
from collections import defaultdict
|
||||
|
||||
# 第三方模块
|
||||
from PyQt4.QtCore import QTimer
|
||||
@ -68,7 +69,7 @@ class EventEngine(object):
|
||||
|
||||
# 这里的__handlers是一个字典,用来保存对应的事件调用关系
|
||||
# 其中每个键对应的值是一个列表,列表中保存了对该事件进行监听的函数功能
|
||||
self.__handlers = {}
|
||||
self.__handlers = defaultdict(list)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def __run(self):
|
||||
@ -128,34 +129,23 @@ class EventEngine(object):
|
||||
#----------------------------------------------------------------------
|
||||
def register(self, type_, handler):
|
||||
"""注册事件处理函数监听"""
|
||||
# 尝试获取该事件类型对应的处理函数列表,若无则创建
|
||||
try:
|
||||
handlerList = self.__handlers[type_]
|
||||
except KeyError:
|
||||
handlerList = []
|
||||
self.__handlers[type_] = handlerList
|
||||
|
||||
# 若要注册的处理器不在该事件的处理器列表中,则注册该事件
|
||||
if handler not in handlerList:
|
||||
handlerList.append(handler)
|
||||
if handler not in self.__handlers[type_]:
|
||||
self.__handlers[type_].append(handler)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def unregister(self, type_, handler):
|
||||
"""注销事件处理函数监听"""
|
||||
# 尝试获取该事件类型对应的处理函数列表,若无则忽略该次注销请求
|
||||
try:
|
||||
handlerList = self.__handlers[type_]
|
||||
handlerList = self.__handlers[type_]
|
||||
|
||||
# 如果该函数存在于列表中,则移除
|
||||
if handler in handlerList:
|
||||
handlerList.remove(handler)
|
||||
|
||||
# 如果函数列表为空,则从引擎中移除该事件类型
|
||||
if not handlerList:
|
||||
del self.__handlers[type_]
|
||||
except KeyError:
|
||||
pass
|
||||
# 如果该函数存在于列表中,则移除
|
||||
if handler in handlerList:
|
||||
handlerList.remove(handler)
|
||||
|
||||
# 如果函数列表为空,则从引擎中移除该事件类型
|
||||
if not handlerList:
|
||||
del self.__handlers[type_]
|
||||
#----------------------------------------------------------------------
|
||||
def put(self, event):
|
||||
"""向事件队列中存入事件"""
|
||||
|
Loading…
Reference in New Issue
Block a user