本人新学PYTHON不久,问了很多人都说PYTHON没有事件机制。。 偶觉得很麻烦,就自己写了一个。
要广播事件就必须继承 EventDispatcher类, 广播的事件必须是Aevent或者其子类。
class EventDispatcher(object):
def __init__(self):
self.events = {}
def addEventListener(self,eventType,listenFunction):
if not self.events.has_key(eventType):
self.events[eventType] = []
eventList = self.events[eventType]
eventList.append(listenFunction)
def removeEventListener(self,eventType,ListenFunction):
if not self.events.has_key(eventType):
return
eventList = self.events[eventType]
eventList.remove(ListenFunction)
def dispatchEvent(self,event):
if not self.events.has_key(event.type):
return
eventList = self.events[event.type]
for fun in eventList:
fun()
def __del__(self):
keys = self.events.keys
for key in keys:
eventList = self.events[key]
for fun in eventList:
del fun
class Aevent(object):
def __init__(self,Type):
self.type = Type使用示例代码
class Obj(EventDispatcher):
def __init__(self):
self.i = 1
EventDispatcher.__init__(self)
def addI(self):
self.i = 1 + self.i
EventDispatcher.dispatchEvent(self,Aevent('iadd'))
def onIadd():
print o.i
o = Obj()
o.addEventListener('iadd',onIadd)
o.addI() #output 2
o.addI() #output 3
o.removeEventListener('iadd',onIadd)
o.addI() #no output