eventmanager.py
1 #-*-encoding:utf-8-*-2 3 #System Module4 fromQueueImportQueue, Empty5 fromThreadingImport*6 7 8 classEventManager:9 def __init__(self):Ten """Initializing the event manager""" One #Event Object List ASelf.__eventqueue=Queue () - #Event Manager Switches -Self.__active=False the #Event Processing Thread -Self.__thread= Thread (target = self.__run) - - #The __handlers here is a dictionary that is used to save the response function of the corresponding event + #where each key corresponds to a list, the list holds a response function to listen to the event, a pair of multiple -Self.__handlers= {}#{Event Type: [Method of Handling event]} + A def __run(self): at """Engine Run""" - whileSelf.__active==True: - Try: - #gets the blocking time of the event set to 1 seconds -event = self.__eventqueue. Get (block = True, timeout = 1) -Self.__eventprocess(Event) in exceptEmpty: - Pass to + def __eventprocess(self, event): - """Handling Events""" the #Check if there is a handler to listen for this event * ifEvent.type_inchSelf.__handlers: $ #if present, the event is passed in order to the handler function executionPanax Notoginseng forHandlerinchSelf.__handlers[Event.type_]: - Handler (event) the + defStart (self): A """Start""" the #set the event manager to start +Self.__active=True - #start the event processing thread $Self.__thread. Start () $ - defStop (self): - """Stop""" the #set the event manager to stop -Self.__active=FalseWuyi #wait for the event processing thread to exit theSelf.__thread. Join () - Wu defAddEventListener (self, Type_, handler): - """binding event and listener handler functions""" About #attempt to get a list of the handler functions for the event type, if none is created $ Try: -Handlerlist = self.__handlers[Type_] - exceptKeyerror: -Handlerlist = [] A +Self.__handlers[Type_] =handlerlist the #to register a processor that is not in the list of processors for this event, register the event - ifHandler not inchhandlerlist: $ Handlerlist.append (handler) the the defRemoveEventListener (self, Type_, handler): the """to remove a handler function from a listener""" the #the reader himself tried to achieve - in defsendevent (Self, event): the """sending events, storing events in the event queue""" theSelf.__eventqueue. Put (event) About the """Event Object""" the classEvent: the def __init__(Self, type_=None): +Self.type_ = Type_#Event Type -Self.dict = {}#dictionaries are used to hold specific event data
test.py
1 #-*-encoding:utf-8-*-2 3 fromThreadingImport*4 fromEventManagerImport*5 Import Time6 7 #Event name new article8Event_artical ="event_artical"9 Ten One #Event Source Public number A classpublicaccounts: - def __init__(Self,eventmanager): -Self.__eventmanager=EventManager the - defwritenewartical (self): - #Event object, writing a new article -event = Event (type_=event_artical) +event.dict["artical"] = u'How to write more elegant code \ n' - #Send Event +Self.__eventmanager. Sendevent (Event) A Print(U'Public number send new article') at - - #Listener Subscribers - classListener: - def __init__(self,username): -Self.__username=username in - #The listener's handler function reads the article to defreadartical (self,event): + Print(U'%s received new article'% self.__username) - Print(U'reading new article content:%s'% event.dict["artical"]) the * $ """test function"""Panax Notoginseng defTest (): -Listner1 = Listener ("Thinkroom")#subscribers 1 theListner2 = Listener ("Steve")#subscribers 2 + AEventManager =EventManager () the + #binding event and listener response functions (new article) - Eventmanager.addeventlistener (event_artical, Listner1. readartical) $ Eventmanager.addeventlistener (event_artical, Listner2. readartical) $ Eventmanager.start () - -PUBLICACC =publicaccounts (EventManager) the whileTrue: - publicacc.writenewartical ()WuyiTime.sleep (2) the - if __name__=='__main__': WuTest ()
Python simulation event triggering mechanism